-- UPDATE policy'yi de anon role'üne aç (email ile profil bulup clerk_user_id bağlama için)
-- Bu sayede Clerk JWT'si authenticated olarak tanınmadan önce de profil güncellenebilir

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 <> ''
  );

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.';
