-- Migration 172: Supplier flow type fields on cases
-- Created: 2026-04-12

ALTER TABLE sag_sager
ADD COLUMN IF NOT EXISTS supplier_flow_type VARCHAR(20),
ADD COLUMN IF NOT EXISTS supplier_flow_confidence NUMERIC(4,3);

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'chk_sag_sager_supplier_flow_type'
    ) THEN
        ALTER TABLE sag_sager
        ADD CONSTRAINT chk_sag_sager_supplier_flow_type
        CHECK (supplier_flow_type IS NULL OR supplier_flow_type IN ('varekob', 'ydelse'));
    END IF;
END $$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'chk_sag_sager_supplier_flow_confidence'
    ) THEN
        ALTER TABLE sag_sager
        ADD CONSTRAINT chk_sag_sager_supplier_flow_confidence
        CHECK (supplier_flow_confidence IS NULL OR (supplier_flow_confidence >= 0 AND supplier_flow_confidence <= 1));
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_sag_sager_supplier_flow_type
ON sag_sager(supplier_flow_type)
WHERE deleted_at IS NULL;

COMMENT ON COLUMN sag_sager.supplier_flow_type IS 'Supplier module type selection: varekob or ydelse';
COMMENT ON COLUMN sag_sager.supplier_flow_confidence IS 'AI suggestion confidence (0-1) for supplier flow type';
