-- Forum Moderation Migration for BroadcastBeat
-- Adds moderation fields to forum_threads and forum_replies

-- ============================================================
-- 1. ADD MODERATION COLUMNS TO forum_threads
-- ============================================================
ALTER TABLE public.forum_threads
    ADD COLUMN IF NOT EXISTS is_pinned BOOLEAN DEFAULT false,
    ADD COLUMN IF NOT EXISTS is_featured BOOLEAN DEFAULT false,
    ADD COLUMN IF NOT EXISTS is_locked BOOLEAN DEFAULT false,
    ADD COLUMN IF NOT EXISTS is_flagged BOOLEAN DEFAULT false,
    ADD COLUMN IF NOT EXISTS flag_reason TEXT,
    ADD COLUMN IF NOT EXISTS moderated_by UUID REFERENCES public.user_profiles(id) ON DELETE SET NULL,
    ADD COLUMN IF NOT EXISTS moderated_at TIMESTAMPTZ;

-- ============================================================
-- 2. ADD MODERATION COLUMNS TO forum_replies
-- ============================================================
ALTER TABLE public.forum_replies
    ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN DEFAULT false,
    ADD COLUMN IF NOT EXISTS is_flagged BOOLEAN DEFAULT false,
    ADD COLUMN IF NOT EXISTS flag_reason TEXT,
    ADD COLUMN IF NOT EXISTS moderated_by UUID REFERENCES public.user_profiles(id) ON DELETE SET NULL,
    ADD COLUMN IF NOT EXISTS moderated_at TIMESTAMPTZ;

-- ============================================================
-- 3. INDEXES FOR MODERATION QUERIES
-- ============================================================
CREATE INDEX IF NOT EXISTS idx_forum_threads_is_pinned ON public.forum_threads(is_pinned) WHERE is_pinned = true;
CREATE INDEX IF NOT EXISTS idx_forum_threads_is_featured ON public.forum_threads(is_featured) WHERE is_featured = true;
CREATE INDEX IF NOT EXISTS idx_forum_threads_is_flagged ON public.forum_threads(is_flagged) WHERE is_flagged = true;
CREATE INDEX IF NOT EXISTS idx_forum_replies_is_flagged ON public.forum_replies(is_flagged) WHERE is_flagged = true;
CREATE INDEX IF NOT EXISTS idx_forum_replies_is_hidden ON public.forum_replies(is_hidden) WHERE is_hidden = true;

-- ============================================================
-- 4. RLS POLICIES FOR MODERATION (admin/service role)
-- ============================================================

-- Allow authenticated users (admins) to update moderation fields on threads
DROP POLICY IF EXISTS "admin_moderate_forum_threads" ON public.forum_threads;
CREATE POLICY "admin_moderate_forum_threads"
ON public.forum_threads FOR UPDATE TO authenticated
USING (true)
WITH CHECK (true);

-- Allow authenticated users (admins) to update moderation fields on replies
DROP POLICY IF EXISTS "admin_moderate_forum_replies" ON public.forum_replies;
CREATE POLICY "admin_moderate_forum_replies"
ON public.forum_replies FOR UPDATE TO authenticated
USING (true)
WITH CHECK (true);
