-- Clerk JWT'si Supabase tarafından authenticated olarak tanınmadan önce
-- profil oluşturabilmek için INSERT policy'yi anon role'üne de aç.
-- clerk_user_id dolu olma şartı korunuyor — rastgele insert önleniyor.

DROP POLICY IF EXISTS "Users can insert own profile" ON profiles;
DROP POLICY IF EXISTS "Authenticated users can create own profile" ON profiles;

-- Hem authenticated (JWT template kurulunca) hem anon (kurulmadan önce) çalışır
CREATE POLICY "Allow profile creation with clerk_user_id"
  ON profiles FOR INSERT
  TO public
  WITH CHECK (
    clerk_user_id IS NOT NULL       -- boş clerk_user_id ile insert yapılamaz
    AND clerk_user_id <> ''
    AND email IS NOT NULL           -- email de zorunlu
  );

-- UPDATE policy'yi de anon role'üne aç (email ile profil bulup clerk_user_id bağlama için)
DROP POLICY IF EXISTS "Users can update own profile" ON profiles;
DROP POLICY IF EXISTS "Unblock muhammet linking" ON profiles;

CREATE POLICY "Allow profile update with email match"
  ON profiles FOR UPDATE
  TO public
  USING (
    email IS NOT NULL               -- email zorunlu
    AND (
      clerk_user_id IS NULL         -- henüz bağlanmamış profiller
      OR clerk_user_id = ''
    )
  )
  WITH CHECK (
    clerk_user_id IS NOT NULL       -- güncelleme sonrası clerk_user_id dolu olmalı
    AND clerk_user_id <> ''
  );

-- Admin tüm profilleri görebilir (mevcut)
DROP POLICY IF EXISTS "Admins can view all profiles" ON profiles;
CREATE POLICY "Admins can view all profiles"
  ON profiles FOR SELECT
  TO authenticated
  USING (is_admin());

COMMENT ON POLICY "Allow profile creation with clerk_user_id" ON profiles IS 
  'Allows profile creation for both anon (before JWT template) and authenticated (after JWT template) roles. Requires clerk_user_id and email to prevent random inserts.';

COMMENT ON POLICY "Allow profile update with email match" ON profiles IS 
  'Allows linking Clerk user ID to existing profiles by email, works for both anon and authenticated roles.';
