-- Migration 169: Supplier invoice -> case traceability and purchase line classification
-- Created: 2026-04-12

-- Link supplier invoices to cases for procurement workflow
ALTER TABLE supplier_invoices
ADD COLUMN IF NOT EXISTS sag_id INTEGER REFERENCES sag_sager(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_supplier_invoices_sag_id
ON supplier_invoices(sag_id);

-- Add explicit purchase line classification + invoice traceability on case purchase lines
ALTER TABLE sag_salgsvarer
ADD COLUMN IF NOT EXISTS purchase_purpose VARCHAR(50),
ADD COLUMN IF NOT EXISTS supplier_invoice_id INTEGER REFERENCES supplier_invoices(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS supplier_invoice_line_id INTEGER REFERENCES supplier_invoice_lines(id) ON DELETE SET NULL;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'chk_sag_salgsvarer_purchase_purpose'
    ) THEN
        ALTER TABLE sag_salgsvarer
        ADD CONSTRAINT chk_sag_salgsvarer_purchase_purpose
        CHECK (
            purchase_purpose IS NULL
            OR purchase_purpose IN (
                'salg',
                'lager',
                'asset',
                'intern_brug',
                'retur_reklamation',
                'projekt_omkostning'
            )
        );
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_sag_salgsvarer_purchase_purpose
ON sag_salgsvarer(purchase_purpose);

CREATE INDEX IF NOT EXISTS idx_sag_salgsvarer_supplier_invoice_id
ON sag_salgsvarer(supplier_invoice_id);

CREATE INDEX IF NOT EXISTS idx_sag_salgsvarer_supplier_invoice_line_id
ON sag_salgsvarer(supplier_invoice_line_id);
