-- Fix RLS policies for forum_topics table
-- Run this in Supabase SQL Editor

-- 1. Drop existing policies if they exist
DROP POLICY IF EXISTS forum_topics_select_all ON public.forum_topics;
DROP POLICY IF EXISTS forum_topics_insert_authenticated ON public.forum_topics;
DROP POLICY IF EXISTS forum_topics_update_author ON public.forum_topics;
DROP POLICY IF EXISTS forum_topics_delete_author ON public.forum_topics;

-- 2. Create new policies
-- Allow everyone to read topics
CREATE POLICY forum_topics_select_all ON public.forum_topics
  FOR SELECT USING (true);

-- Allow authenticated users to create topics
CREATE POLICY forum_topics_insert_authenticated ON public.forum_topics
  FOR INSERT WITH CHECK (auth.role() = 'authenticated');

-- Allow authors to update their own topics
CREATE POLICY forum_topics_update_author ON public.forum_topics
  FOR UPDATE USING (auth.uid() = author_id);

-- Allow authors to delete their own topics
CREATE POLICY forum_topics_delete_author ON public.forum_topics
  FOR DELETE USING (auth.uid() = author_id);

-- 3. Also fix RLS policies for forum_replies
DROP POLICY IF EXISTS forum_replies_select_all ON public.forum_replies;
DROP POLICY IF EXISTS forum_replies_insert_authenticated ON public.forum_replies;
DROP POLICY IF EXISTS forum_replies_update_author ON public.forum_replies;
DROP POLICY IF EXISTS forum_replies_delete_author ON public.forum_replies;

CREATE POLICY forum_replies_select_all ON public.forum_replies
  FOR SELECT USING (true);

CREATE POLICY forum_replies_insert_authenticated ON public.forum_replies
  FOR INSERT WITH CHECK (auth.role() = 'authenticated');

CREATE POLICY forum_replies_update_author ON public.forum_replies
  FOR UPDATE USING (auth.uid() = author_id);

CREATE POLICY forum_replies_delete_author ON public.forum_replies
  FOR DELETE USING (auth.uid() = author_id);

-- 4. Fix RLS policies for forum_upvotes
DROP POLICY IF EXISTS forum_upvotes_select_all ON public.forum_upvotes;
DROP POLICY IF EXISTS forum_upvotes_insert_authenticated ON public.forum_upvotes;
DROP POLICY IF EXISTS forum_upvotes_delete_authenticated ON public.forum_upvotes;

CREATE POLICY forum_upvotes_select_all ON public.forum_upvotes
  FOR SELECT USING (true);

CREATE POLICY forum_upvotes_insert_authenticated ON public.forum_upvotes
  FOR INSERT WITH CHECK (auth.role() = 'authenticated');

CREATE POLICY forum_upvotes_delete_authenticated ON public.forum_upvotes
  FOR DELETE USING (auth.uid() = user_id);

-- 5. Make sure RLS is enabled on all tables
ALTER TABLE public.forum_topics ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.forum_replies ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.forum_upvotes ENABLE ROW LEVEL SECURITY;
