-- Migration: Enforce unique economic customer number on customers
-- Prevents ambiguous mapping during e-conomic sync

-- Normalize values before uniqueness check (only for text-like columns)
DO $$
DECLARE
        column_data_type TEXT;
BEGIN
        SELECT data_type
        INTO column_data_type
        FROM information_schema.columns
        WHERE table_schema = 'public'
            AND table_name = 'customers'
            AND column_name = 'economic_customer_number';

        IF column_data_type IN ('character varying', 'character', 'text') THEN
                EXECUTE $$
                        UPDATE customers
                        SET economic_customer_number = NULL
                        WHERE economic_customer_number IS NOT NULL
                            AND btrim(economic_customer_number) = ''
                $$;

                EXECUTE $$
                        UPDATE customers
                        SET economic_customer_number = btrim(economic_customer_number)
                        WHERE economic_customer_number IS NOT NULL
                $$;
        END IF;
END $$;

-- Abort migration if duplicates exist (must be manually resolved first)
DO $$
DECLARE
    duplicate_value TEXT;
    duplicate_count INTEGER;
BEGIN
    SELECT economic_customer_number, COUNT(*)::INTEGER
    INTO duplicate_value, duplicate_count
    FROM customers
    WHERE economic_customer_number IS NOT NULL
    GROUP BY economic_customer_number
    HAVING COUNT(*) > 1
    ORDER BY COUNT(*) DESC, economic_customer_number
    LIMIT 1;

    IF duplicate_value IS NOT NULL THEN
        RAISE EXCEPTION 'Cannot create unique index on customers.economic_customer_number. Duplicate value: % (count=%). Resolve duplicates and rerun migration.', duplicate_value, duplicate_count;
    END IF;
END $$;

-- Enforce uniqueness for non-null values
CREATE UNIQUE INDEX IF NOT EXISTS customers_economic_customer_number_unique_idx
ON customers (economic_customer_number)
WHERE economic_customer_number IS NOT NULL;

COMMENT ON INDEX customers_economic_customer_number_unique_idx IS
'Ensures e-conomic customer numbers are unique to prevent sync mismatch.';
