-- Configure Realtime access for moderation tables
-- Ensure tables have proper replica identity
ALTER TABLE content_submissions REPLICA IDENTITY FULL;
ALTER TABLE submission_items REPLICA IDENTITY FULL;
ALTER TABLE reports REPLICA IDENTITY FULL;
ALTER TABLE reviews REPLICA IDENTITY FULL;

-- Add tables to realtime publication if not already added
DO $$
BEGIN
  -- Add content_submissions
  IF NOT EXISTS (
    SELECT 1 FROM pg_publication_tables 
    WHERE pubname = 'supabase_realtime' 
    AND schemaname = 'public' 
    AND tablename = 'content_submissions'
  ) THEN
    ALTER PUBLICATION supabase_realtime ADD TABLE content_submissions;
  END IF;

  -- Add submission_items
  IF NOT EXISTS (
    SELECT 1 FROM pg_publication_tables 
    WHERE pubname = 'supabase_realtime' 
    AND schemaname = 'public' 
    AND tablename = 'submission_items'
  ) THEN
    ALTER PUBLICATION supabase_realtime ADD TABLE submission_items;
  END IF;

  -- Add reports
  IF NOT EXISTS (
    SELECT 1 FROM pg_publication_tables 
    WHERE pubname = 'supabase_realtime' 
    AND schemaname = 'public' 
    AND tablename = 'reports'
  ) THEN
    ALTER PUBLICATION supabase_realtime ADD TABLE reports;
  END IF;

  -- Add reviews
  IF NOT EXISTS (
    SELECT 1 FROM pg_publication_tables 
    WHERE pubname = 'supabase_realtime' 
    AND schemaname = 'public' 
    AND tablename = 'reviews'
  ) THEN
    ALTER PUBLICATION supabase_realtime ADD TABLE reviews;
  END IF;
END $$;

-- Verify configuration
SELECT 
  schemaname, 
  tablename,
  pubname
FROM pg_publication_tables 
WHERE pubname = 'supabase_realtime' 
AND schemaname = 'public'
ORDER BY tablename;