-- Helper script to diagnose teacher insert permissions for training_stream_events
-- Update the constants below before running in Supabase SQL editor or psql.

-- >>> configure these for the teacher experiencing RLS failures <<<
WITH params AS (
    -- Replace the UUID literals below before running
    SELECT
        '7bf7378e-a027-473e-97ac-3460ed3f170a'::uuid AS teacher_auth_id,
        'bc333301-78cd-4ef0-a123-456789012345'::uuid AS target_class_id
),
teacher AS (
    SELECT u.id AS user_id,
           u.auth_id,
           u.username,
           u.email
    FROM public.ak_users u
    JOIN params p ON u.auth_id = p.teacher_auth_id
),
teacher_roles AS (
    SELECT tr.id,
           tr.user_id,
           tr.class_id,
           tr.role,
           tr.created_at
    FROM public.ak_teacher_roles tr
    JOIN teacher t ON t.user_id = tr.user_id
),
class_match AS (
    SELECT tr.id,
           tr.class_id,
           c.name AS class_name
    FROM teacher_roles tr
    LEFT JOIN public.ak_classes c ON c.id = tr.class_id
    JOIN params p ON tr.class_id = p.target_class_id
)
SELECT
    (SELECT to_jsonb(t) FROM teacher t) AS teacher_account,
    (SELECT COALESCE(jsonb_agg(to_jsonb(tr)), '[]'::jsonb) FROM teacher_roles tr) AS all_teacher_roles,
    (SELECT to_jsonb(cm) FROM class_match cm LIMIT 1) AS target_class_role,
    EXISTS (
        SELECT 1
        FROM teacher t
        JOIN public.ak_teacher_roles tr ON tr.user_id = t.user_id
        JOIN params p ON tr.class_id = p.target_class_id
    ) AS has_class_assignment;

-- Next steps based on results:
-- 1. If teacher_account is null: insert the Supabase auth user into ak_users (see migrate scripts).
-- 2. If has_class_assignment is false: insert a row into ak_teacher_roles mapping the teacher to the class.
-- 3. After fixing data, retry the insert from the teacher client.
