DO $$
DECLARE
    target_user_id uuid;
    target_email text := 'kenan_karaerr@hotmail.com';
BEGIN
    -- 1. Find the user ID from auth.users
    SELECT id INTO target_user_id
    FROM auth.users
    WHERE email = target_email;

    IF target_user_id IS NULL THEN
        RAISE NOTICE 'User % not found in auth.users', target_email;
    ELSE
        RAISE NOTICE 'Found user % with ID %', target_email, target_user_id;

        -- 2. Ensure user exists in public.profiles (Required for Logs)
        INSERT INTO public.profiles (id, full_name, role)
        VALUES (target_user_id, 'Kenan Karaer', 'admin')
        ON CONFLICT (id) DO UPDATE
        SET role = 'admin',
            full_name = EXCLUDED.full_name;

        -- 3. Add to public.customers (Requested by user)
        -- Check if customer exists with this email to avoid duplicates
        IF NOT EXISTS (SELECT 1 FROM public.customers WHERE email = target_email) THEN
            INSERT INTO public.customers (full_name, email, notes)
            VALUES ('Kenan Karaer', target_email, 'Admin User - Added via migration');
            RAISE NOTICE 'Added user to customers table.';
        ELSE
            RAISE NOTICE 'User already exists in customers table.';
        END IF;

    END IF;
END $$;
