-- ============================================================================
-- Migration 055: Fix ambiguous column reference i link_tmodule_customers_to_hub
-- ============================================================================
-- Retter SQL fejl hvor tmodule_id var ambiguous i subquery
-- ============================================================================

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 NOT EXISTS (SELECT 1 FROM economic_matches em WHERE em.tmodule_id = tc.id)
    ),
    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;

COMMENT ON FUNCTION link_tmodule_customers_to_hub() IS 
'Linker tmodule_customers til Hub customers via economic_customer_number (prioritet) eller navn match (fallback). Fixed ambiguous column reference.';
