-- Fix missing user profiles and permissions

-- 1. Ensure all auth users have a profile in public.users
-- This backfills any users that might have been created when the trigger wasn't working
insert into public.users (id, email, role, display_name)
select 
  id, 
  email, 
  coalesce(raw_user_meta_data->>'role', 'organizer'), 
  coalesce(raw_user_meta_data->>'display_name', split_part(email, '@', 1))
from auth.users
where id not in (select id from public.users)
on conflict (id) do nothing;

-- 2. Specifically ensure sheldon@blueguruz.com is an organizer
-- This fixes the issue where the user might have been created with the wrong role or no role
update public.users
set role = 'organizer'
where email = 'sheldon@blueguruz.com';

-- 3. Update metadata for consistency (optional but good for client-side checks)
update auth.users
set raw_user_meta_data = 
  case 
    when raw_user_meta_data is null then jsonb_build_object('role', 'organizer')
    else raw_user_meta_data || jsonb_build_object('role', 'organizer')
  end
where email = 'sheldon@blueguruz.com';
