-- Migration 176: Supplier invoice generic relations
-- Created: 2026-04-13

CREATE TABLE IF NOT EXISTS supplier_invoice_relations (
    id BIGSERIAL PRIMARY KEY,
    supplier_invoice_id INTEGER NOT NULL REFERENCES supplier_invoices(id) ON DELETE CASCADE,
    relation_type VARCHAR(40) NOT NULL,
    relation_id BIGINT NOT NULL,
    is_primary BOOLEAN NOT NULL DEFAULT FALSE,
    note TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'chk_supplier_invoice_relations_relation_type'
    ) THEN
        ALTER TABLE supplier_invoice_relations
        ADD CONSTRAINT chk_supplier_invoice_relations_relation_type
        CHECK (
            relation_type IN ('sag', 'kunde', 'ordre', 'asset', 'reklamation_sag', 'email')
        );
    END IF;
END $$;

CREATE UNIQUE INDEX IF NOT EXISTS uq_supplier_invoice_relations_type_id
ON supplier_invoice_relations(supplier_invoice_id, relation_type, relation_id);

CREATE INDEX IF NOT EXISTS idx_supplier_invoice_relations_lookup
ON supplier_invoice_relations(relation_type, relation_id);

CREATE UNIQUE INDEX IF NOT EXISTS uq_supplier_invoice_relations_primary_per_type
ON supplier_invoice_relations(supplier_invoice_id, relation_type)
WHERE is_primary = TRUE;

COMMENT ON TABLE supplier_invoice_relations IS 'Generic relation map from supplier invoices to related entities';
COMMENT ON COLUMN supplier_invoice_relations.relation_type IS 'Relation type: sag, kunde, ordre, asset, reklamation_sag, email';
COMMENT ON COLUMN supplier_invoice_relations.relation_id IS 'Id of the related entity';
COMMENT ON COLUMN supplier_invoice_relations.is_primary IS 'Primary relation flag within relation type';
