-- Fix RLS policies on photo_submissions and photo_submission_items
-- Replace direct auth.mfa_factors queries with has_mfa_enabled() security definer function
-- This prevents "permission denied for table mfa_factors" errors

-- ============================================
-- Photo Submissions Table
-- ============================================

DROP POLICY IF EXISTS "Moderators can view all photo submissions" ON public.photo_submissions;
DROP POLICY IF EXISTS "Moderators can update photo submissions" ON public.photo_submissions;
DROP POLICY IF EXISTS "Moderators can delete photo submissions" ON public.photo_submissions;

CREATE POLICY "Moderators can view all photo submissions"
ON public.photo_submissions
FOR SELECT
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    (NOT has_mfa_enabled(auth.uid())) OR has_aal2()
  )
);

CREATE POLICY "Moderators can update photo submissions"
ON public.photo_submissions
FOR UPDATE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    (NOT has_mfa_enabled(auth.uid())) OR has_aal2()
  )
);

CREATE POLICY "Moderators can delete photo submissions"
ON public.photo_submissions
FOR DELETE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    (NOT has_mfa_enabled(auth.uid())) OR has_aal2()
  )
);

-- ============================================
-- Photo Submission Items Table
-- ============================================

DROP POLICY IF EXISTS "Moderators can view all photo submission items" ON public.photo_submission_items;
DROP POLICY IF EXISTS "Moderators can update photo submission items" ON public.photo_submission_items;
DROP POLICY IF EXISTS "Moderators can delete photo submission items" ON public.photo_submission_items;

CREATE POLICY "Moderators can view all photo submission items"
ON public.photo_submission_items
FOR SELECT
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    (NOT has_mfa_enabled(auth.uid())) OR has_aal2()
  )
);

CREATE POLICY "Moderators can update photo submission items"
ON public.photo_submission_items
FOR UPDATE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    (NOT has_mfa_enabled(auth.uid())) OR has_aal2()
  )
);

CREATE POLICY "Moderators can delete photo submission items"
ON public.photo_submission_items
FOR DELETE
TO authenticated
USING (
  is_moderator(auth.uid()) AND (
    (NOT has_mfa_enabled(auth.uid())) OR has_aal2()
  )
);