-- Fix admin role assignment broken by migration 017
-- ============================================
-- Problem: Migration 017's WITH CHECK prevents admins from updating other members' roles
-- because the only UPDATE policy on members requires auth.uid() = id.
-- Solution: Replace the overly restrictive policy with a properly scoped one,
-- and add a separate policy for admins to update any member.

-- Drop the problematic policy from 017 if it exists
DROP POLICY IF EXISTS "Users can update own profile" ON public.members;

-- Also drop by the name used in 017 re-creation (same name, just being safe)
DROP POLICY IF EXISTS "Members can update own non-role fields" ON public.members;

-- Allow members to update their own non-role fields (profile info)
CREATE POLICY "Members can update own profile"
  ON public.members
  FOR UPDATE
  TO authenticated
  USING (auth.uid() = id)
  WITH CHECK (
    auth.uid() = id
    AND role = (SELECT role FROM public.members WHERE id = auth.uid())
  );

-- Allow admins to update any member (including role changes) EXCEPT their own role
CREATE POLICY "Admins can update other members"
  ON public.members
  FOR UPDATE
  TO authenticated
  USING (
    EXISTS (
      SELECT 1 FROM public.members
      WHERE id = auth.uid() AND role = 'admin'
    )
  )
  WITH CHECK (
    -- Admins can change any field on other members
    (id != auth.uid())
    OR
    -- On their own record, admins can update non-role fields (role must stay the same)
    (id = auth.uid() AND role = (SELECT role FROM public.members WHERE id = auth.uid()))
  );
