-- Migration 017: Fix RLS policy to prevent self-role-escalation
-- The "Users can update own profile" policy allows users to SET role = 'admin'
-- on their own row because it lacks a WITH CHECK clause restricting role changes.

-- Drop the existing policy
DROP POLICY IF EXISTS "Users can update own profile" ON public.members;

-- Recreate with WITH CHECK that prevents role changes
CREATE POLICY "Users can update own profile"
  ON public.members FOR UPDATE
  TO authenticated
  USING (auth.uid() = id)
  WITH CHECK (
    auth.uid() = id
    AND role = (SELECT m.role FROM public.members m WHERE m.id = auth.uid())
  );
