-- Fix: Allow authenticated users to view public profiles
-- The filtered_profiles view handles field-level privacy filtering

-- Drop the confusingly named policy that doesn't actually use the filtered view
DROP POLICY IF EXISTS "Users view own profile or use filtered view" ON public.profiles;

-- Add a new policy that allows viewing public, non-banned profiles
-- The filtered_profiles view will handle granular field-level access control
CREATE POLICY "Authenticated users can view public profiles"
ON public.profiles
FOR SELECT
TO authenticated
USING (
  -- Users can always see their own profile completely
  (auth.uid() = user_id) 
  OR 
  -- Users can see public profiles that aren't banned
  (privacy_level = 'public' AND NOT banned)
  OR
  -- Moderators can see all profiles
  is_moderator(auth.uid())
);

-- Add comment explaining the security model
COMMENT ON POLICY "Authenticated users can view public profiles" ON public.profiles IS 
'Allows authenticated users to view public profiles. 
Sensitive fields should be accessed through the filtered_profiles view which enforces granular privacy controls.
Users can always see their own complete profile.
Moderators can see all profiles.
Banned profiles are hidden from regular users.';