-- ============================================================================
-- Migration 054: Forbedret kunde-linking med economic_customer_number
-- ============================================================================
-- Opdaterer linking logik til at prioritere economic_customer_number match
-- over navn match for mere robust kunde-identifikation
-- ============================================================================

-- Drop og genopret linking funktion med economic nummer prioritering
DROP FUNCTION IF EXISTS link_tmodule_customers_to_hub();

CREATE OR REPLACE FUNCTION link_tmodule_customers_to_hub()
RETURNS TABLE (
    tmodule_id INTEGER,
    tmodule_name TEXT,
    hub_id INTEGER,
    hub_name TEXT,
    action TEXT
) AS $$
BEGIN
    RETURN QUERY
    WITH economic_matches AS (
        -- Prioriter economic_customer_number match (mest præcis)
        SELECT 
            tc.id as tmodule_id,
            tc.name::TEXT as tmodule_name,
            c.id as hub_id,
            c.name::TEXT as hub_name,
            'economic_number_match'::TEXT as action
        FROM tmodule_customers tc
        JOIN customers c ON tc.economic_customer_number = c.economic_customer_number
        WHERE tc.hub_customer_id IS NULL
          AND tc.economic_customer_number IS NOT NULL
          AND c.economic_customer_number IS NOT NULL
    ),
    name_matches AS (
        -- Fallback til navn match for kunder uden economic nummer
        SELECT 
            tc.id as tmodule_id,
            tc.name::TEXT as tmodule_name,
            c.id as hub_id,
            c.name::TEXT as hub_name,
            'name_match'::TEXT as action
        FROM tmodule_customers tc
        JOIN customers c ON LOWER(TRIM(tc.name)) = LOWER(TRIM(c.name))
        WHERE tc.hub_customer_id IS NULL
          AND tc.id NOT IN (SELECT tmodule_id FROM economic_matches)
    ),
    all_matches AS (
        SELECT * FROM economic_matches
        UNION ALL
        SELECT * FROM name_matches
    ),
    updates AS (
        -- Opdater tmodule_customers med hub_customer_id
        UPDATE tmodule_customers tc
        SET hub_customer_id = m.hub_id,
            updated_at = CURRENT_TIMESTAMP
        FROM all_matches m
        WHERE tc.id = m.tmodule_id
        RETURNING tc.id, tc.name::TEXT, m.hub_id, m.hub_name, m.action
    )
    SELECT * FROM updates;
END;
$$ LANGUAGE plpgsql;

-- Opdater trigger til at tjekke både economic nummer og navn
DROP TRIGGER IF EXISTS auto_link_tmodule_customer ON tmodule_customers;

CREATE OR REPLACE FUNCTION auto_link_tmodule_customer()
RETURNS TRIGGER AS $$
DECLARE
    matched_hub_id INTEGER;
BEGIN
    -- Hvis hub_customer_id allerede er sat, skip
    IF NEW.hub_customer_id IS NOT NULL THEN
        RETURN NEW;
    END IF;
    
    -- Først: prøv at matche på economic_customer_number (mest præcis)
    IF NEW.economic_customer_number IS NOT NULL THEN
        SELECT id INTO matched_hub_id
        FROM customers
        WHERE economic_customer_number = NEW.economic_customer_number
        LIMIT 1;
        
        IF matched_hub_id IS NOT NULL THEN
            NEW.hub_customer_id := matched_hub_id;
            RAISE NOTICE 'Auto-linked tmodule_customer % to hub customer % via economic number %', 
                NEW.name, matched_hub_id, NEW.economic_customer_number;
            RETURN NEW;
        END IF;
    END IF;
    
    -- Fallback: prøv navn match
    SELECT id INTO matched_hub_id
    FROM customers
    WHERE LOWER(TRIM(name)) = LOWER(TRIM(NEW.name))
    LIMIT 1;
    
    IF matched_hub_id IS NOT NULL THEN
        NEW.hub_customer_id := matched_hub_id;
        RAISE NOTICE 'Auto-linked tmodule_customer % to hub customer % via name match', 
            NEW.name, matched_hub_id;
    END IF;
    
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER auto_link_tmodule_customer
    BEFORE INSERT OR UPDATE ON tmodule_customers
    FOR EACH ROW
    EXECUTE FUNCTION auto_link_tmodule_customer();

-- Kør linking for eksisterende kunder (re-link alle)
DO $$
DECLARE
    link_result RECORD;
    total_linked INTEGER := 0;
BEGIN
    RAISE NOTICE 'Starting customer linking...';
    
    FOR link_result IN SELECT * FROM link_tmodule_customers_to_hub() LOOP
        RAISE NOTICE 'Linked: % (tmodule_id=%) -> % (hub_id=%) via %',
            link_result.tmodule_name,
            link_result.tmodule_id,
            link_result.hub_name,
            link_result.hub_id,
            link_result.action;
        total_linked := total_linked + 1;
    END LOOP;
    
    RAISE NOTICE 'Customer linking complete. Total linked: %', total_linked;
END $$;
