-- Add AAL2 enforcement for users with MFA enrolled
-- This provides defense-in-depth at the database level

-- Update RLS policy on content_submissions to enforce AAL2 for moderators
DROP POLICY IF EXISTS "Moderators can view all submissions" ON public.content_submissions;
CREATE POLICY "Moderators can view all submissions"
ON public.content_submissions
FOR SELECT
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    -- Allow if user doesn't have MFA OR has AAL2
    NOT EXISTS (
      SELECT 1 FROM auth.mfa_factors
      WHERE user_id = auth.uid() AND status = 'verified'
    ) OR has_aal2()
  )
);

DROP POLICY IF EXISTS "Moderators can update submissions" ON public.content_submissions;
CREATE POLICY "Moderators can update submissions"
ON public.content_submissions
FOR UPDATE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    NOT EXISTS (
      SELECT 1 FROM auth.mfa_factors
      WHERE user_id = auth.uid() AND status = 'verified'
    ) OR has_aal2()
  )
);

-- Apply same enforcement to submission_items
DROP POLICY IF EXISTS "Moderators can update submission items" ON public.submission_items;
CREATE POLICY "Moderators can update submission items"
ON public.submission_items
FOR UPDATE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    NOT EXISTS (
      SELECT 1 FROM auth.mfa_factors
      WHERE user_id = auth.uid() AND status = 'verified'
    ) OR has_aal2()
  )
);

DROP POLICY IF EXISTS "Moderators can delete submission items" ON public.submission_items;
CREATE POLICY "Moderators can delete submission items"
ON public.submission_items
FOR DELETE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    NOT EXISTS (
      SELECT 1 FROM auth.mfa_factors
      WHERE user_id = auth.uid() AND status = 'verified'
    ) OR has_aal2()
  )
);

-- Apply same enforcement to user_roles table for role management
DROP POLICY IF EXISTS "Moderators can manage roles" ON public.user_roles;
CREATE POLICY "Moderators can manage roles"
ON public.user_roles
FOR ALL
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    NOT EXISTS (
      SELECT 1 FROM auth.mfa_factors
      WHERE user_id = auth.uid() AND status = 'verified'
    ) OR has_aal2()
  )
);