-- Add reply columns to community_messages table
ALTER TABLE IF EXISTS public.community_messages ADD COLUMN IF NOT EXISTS reply_to_id text;
ALTER TABLE IF EXISTS public.community_messages ADD COLUMN IF NOT EXISTS reply_to_content text;
ALTER TABLE IF EXISTS public.community_messages ADD COLUMN IF NOT EXISTS reply_to_sender_email text;

-- Create index for faster reply lookups
CREATE INDEX IF NOT EXISTS idx_community_messages_reply_to_id ON public.community_messages (reply_to_id);

-- Update RLS policies (create if not exists or replace if exists)
DROP POLICY IF EXISTS "Enable read access for all users" ON public.community_messages;
CREATE POLICY "Enable read access for all users" ON public.community_messages
  FOR SELECT
  USING (true);
  
DROP POLICY IF EXISTS "Enable insert for authenticated users only" ON public.community_messages;
CREATE POLICY "Enable insert for authenticated users only" ON public.community_messages
  FOR INSERT
  TO authenticated
  WITH CHECK (auth.role() = 'authenticated');

-- Grant access to the new columns
GRANT ALL ON public.community_messages TO authenticated;
GRANT ALL ON public.community_messages TO service_role; 