-- Allow users to insert their own profile
CREATE POLICY "Users can insert own profile"
  ON profiles FOR INSERT
  TO authenticated
  WITH CHECK (clerk_user_id = get_clerk_user_id());

-- Also allow service role (though it's already allowed)
-- And ensure public can insert if needed for guest/initial sync
-- But for Clerk integration, authenticated is enough.

-- Fix is_admin to be more robust
CREATE OR REPLACE FUNCTION is_admin()
RETURNS BOOLEAN AS $$
DECLARE
  v_clerk_id TEXT;
  v_supabase_id UUID;
BEGIN
  v_clerk_id := get_clerk_user_id();
  v_supabase_id := auth.uid();
  
  RETURN EXISTS (
    SELECT 1 FROM profiles 
    WHERE (
      (v_clerk_id IS NOT NULL AND clerk_user_id = v_clerk_id)
      OR 
      (v_supabase_id IS NOT NULL AND id = v_supabase_id)
    ) 
    AND role = 'admin'
  );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
