-- Migration 051: Fix is_mentor function type mismatch
-- Issue: bigint = text error when comparing telegram_user_id

DROP FUNCTION IF EXISTS is_mentor(text, text);

CREATE FUNCTION is_mentor(
    p_telegram_user_id TEXT,
    p_telegram_username TEXT
) RETURNS BOOLEAN AS $$
DECLARE
    user_id_num BIGINT;
BEGIN
    -- Safely convert telegram_user_id to bigint if it's numeric
    IF p_telegram_user_id IS NOT NULL AND p_telegram_user_id ~ '^[0-9]+$' THEN
        user_id_num := p_telegram_user_id::BIGINT;
    ELSE
        user_id_num := NULL;
    END IF;
    
    RETURN EXISTS (
        SELECT 1 FROM helion_mentors 
        WHERE active = true
        AND (
            -- Match by telegram user ID (bigint)
            (user_id_num IS NOT NULL AND telegram_user_id = user_id_num)
            OR 
            -- Match by username (with or without @)
            (p_telegram_username IS NOT NULL AND username = p_telegram_username)
            OR
            (p_telegram_username IS NOT NULL AND username = '@' || p_telegram_username)
        )
    );
END;
$$ LANGUAGE plpgsql;

-- Test the function
SELECT is_mentor('1642840513', 'ivantytar') as test_by_id;
SELECT is_mentor(NULL, 'ivantytar') as test_by_username;
SELECT is_mentor(NULL, 'unknown_user') as test_not_mentor;
