-- ───────────────────────────────────────────────────────────
-- Fix storage policies:
-- 1. Add missing UPDATE policy for face-enrollment (needed for upsert)
-- 2. Remove recursive profiles subqueries from SELECT policies
-- ───────────────────────────────────────────────────────────

-- face-enrollment: allow users to UPDATE (overwrite) their own face photo
DROP POLICY IF EXISTS "Users can update own face" ON storage.objects;
CREATE POLICY "Users can update own face"
  ON storage.objects FOR UPDATE
  USING (
    bucket_id = 'face-enrollment'
    AND (storage.foldername(name))[1] = auth.uid()::text
  );

-- face-enrollment: fix SELECT to remove recursive profiles subquery
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
  );

-- attendance-verification: allow users to UPDATE (overwrite) their own photo
DROP POLICY IF EXISTS "Users can update verification photo" ON storage.objects;
CREATE POLICY "Users can update verification photo"
  ON storage.objects FOR UPDATE
  USING (
    bucket_id = 'attendance-verification'
    AND (storage.foldername(name))[1] = auth.uid()::text
  );

-- attendance-verification: fix SELECT to remove recursive profiles subquery
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
  );
