-- 1. Grant usage and select privileges to authenticated users
GRANT USAGE ON SCHEMA public TO authenticated;
GRANT ALL ON ALL TABLES IN SCHEMA public TO authenticated;
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO authenticated;

-- 2. Relax RLS policies to allow authenticated users to see the structure
-- We will temporarily downgrade the strict chat_members RLS so you can actually 
-- see the chats before we build the admin UI to add users to chats.

drop policy if exists "Members can view members of their chats." on chat_members;
create policy "Authenticated users can view members" on chat_members for select using ((select auth.role()) = 'authenticated');

drop policy if exists "Sub-chats viewable by chat members." on sub_chats;
create policy "Sub-chats viewable by authenticated users" on sub_chats for select using ((select auth.role()) = 'authenticated');

drop policy if exists "Messages viewable by chat members." on messages;
create policy "Messages viewable by authenticated users" on messages for select using ((select auth.role()) = 'authenticated');

-- Keep insert restrictions but allow basic usage
drop policy if exists "Members can insert messages." on messages;
create policy "Authenticated users can insert messages" on messages for insert with check ((select auth.uid()) = user_id);

-- Finally, notify API to reload
NOTIFY pgrst, 'reload schema';
