-- RLS policies for swap_request_participants
-- Allow participants, swap owners and admins/dispatchers to view/insert participant rows

ALTER TABLE public.swap_request_participants ENABLE ROW LEVEL SECURITY;

-- SELECT: participants, swap requester/recipient, admins/dispatchers
DROP POLICY IF EXISTS "Swap participants: select" ON public.swap_request_participants;
CREATE POLICY "Swap participants: select" ON public.swap_request_participants
  FOR SELECT
  USING (
    user_id = auth.uid()
    OR EXISTS (
      SELECT 1 FROM public.profiles p WHERE p.id = auth.uid() AND p.role IN ('admin','dispatcher')
    )
    OR EXISTS (
      SELECT 1 FROM public.swap_requests s WHERE s.id = swap_request_id AND (s.requester_id = auth.uid() OR s.recipient_id = auth.uid())
    )
  );

-- INSERT: allow user to insert their own participant row, or allow admins/dispatchers
DROP POLICY IF EXISTS "Swap participants: insert" ON public.swap_request_participants;
CREATE POLICY "Swap participants: insert" ON public.swap_request_participants
  FOR INSERT
  WITH CHECK (
    user_id = auth.uid()
    OR EXISTS (
      SELECT 1 FROM public.profiles p WHERE p.id = auth.uid() AND p.role IN ('admin','dispatcher')
    )
  );

-- UPDATE/DELETE: only admins can modify or remove participant rows
DROP POLICY IF EXISTS "Swap participants: admin manage" ON public.swap_request_participants;
CREATE POLICY "Swap participants: admin manage" ON public.swap_request_participants
  FOR ALL
  USING (
    EXISTS (
      SELECT 1 FROM public.profiles p WHERE p.id = auth.uid() AND p.role = 'admin'
    )
  )
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.profiles p WHERE p.id = auth.uid() AND p.role = 'admin'
    )
  );
