-- BMC Office Subscriptions
-- Gemmer abonnementsdata importeret fra BMC Office system

CREATE TABLE IF NOT EXISTS bmc_office_subscriptions (
    id SERIAL PRIMARY KEY,
    customer_id INTEGER REFERENCES customers(id) ON DELETE CASCADE,
    
    -- BMC Office data
    firma_id VARCHAR(50),  -- FirmaID fra BMC Office
    firma_name VARCHAR(255),  -- Firma navn
    start_date DATE,  -- Startdate
    text VARCHAR(500),  -- Produkt/service beskrivelse
    antal DECIMAL(10,2) DEFAULT 1,  -- Antal
    pris DECIMAL(10,2),  -- Pris per enhed
    rabat DECIMAL(10,2) DEFAULT 0,  -- Rabat i DKK
    beskrivelse TEXT,  -- Ekstra beskrivelse/noter
    
    -- Faktura info
    faktura_firma_id VARCHAR(50),  -- FakturaFirmaID
    faktura_firma_name VARCHAR(255),  -- Fakturafirma navn
    
    -- Status
    active BOOLEAN DEFAULT TRUE,
    
    -- Metadata
    imported_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_bmc_office_subs_customer ON bmc_office_subscriptions(customer_id);
CREATE INDEX IF NOT EXISTS idx_bmc_office_subs_firma_id ON bmc_office_subscriptions(firma_id);
CREATE INDEX IF NOT EXISTS idx_bmc_office_subs_faktura_firma_id ON bmc_office_subscriptions(faktura_firma_id);
CREATE INDEX IF NOT EXISTS idx_bmc_office_subs_active ON bmc_office_subscriptions(active);

-- View for calculating totals
CREATE OR REPLACE VIEW bmc_office_subscription_totals AS
SELECT 
    id,
    customer_id,
    firma_id,
    firma_name,
    text,
    antal,
    pris,
    rabat,
    (antal * pris) - rabat AS subtotal,
    ((antal * pris) - rabat) * 1.25 AS total_inkl_moms,
    start_date,
    beskrivelse,
    faktura_firma_name,
    active
FROM bmc_office_subscriptions
WHERE deleted_at IS NULL;

COMMENT ON TABLE bmc_office_subscriptions IS 'Abonnementer importeret fra BMC Office legacy system';
COMMENT ON VIEW bmc_office_subscription_totals IS 'Beregner subtotal og total inkl. moms for BMC Office abonnementer';
