-- ───────────────────────────────────────────────────────────
-- Fix storage SELECT policies so admin, dispatcher, and it_staff
-- can view any user's face-enrollment and attendance-verification photos.
-- Regular users can still only view their own.
-- ───────────────────────────────────────────────────────────

-- face-enrollment: owner OR privileged roles can view
DROP POLICY IF EXISTS "Users can view own face" ON storage.objects;
CREATE POLICY "Users can view own face"
  ON storage.objects FOR SELECT
  USING (
    bucket_id = 'face-enrollment'
    AND (
      (storage.foldername(name))[1] = auth.uid()::text
      OR EXISTS (
        SELECT 1 FROM public.profiles
        WHERE id = auth.uid()
          AND role IN ('admin', 'dispatcher', 'it_staff')
      )
    )
  );

-- attendance-verification: owner OR privileged roles can view
DROP POLICY IF EXISTS "Users and admins can view verification photos" ON storage.objects;
CREATE POLICY "Users and admins can view verification photos"
  ON storage.objects FOR SELECT
  USING (
    bucket_id = 'attendance-verification'
    AND (
      (storage.foldername(name))[1] = auth.uid()::text
      OR EXISTS (
        SELECT 1 FROM public.profiles
        WHERE id = auth.uid()
          AND role IN ('admin', 'dispatcher', 'it_staff')
      )
    )
  );
