-- ============================================================
-- Migration 055: Fix infinite recursion in org_members SELECT policy
-- The previous policy queried org_members from within its own
-- SELECT policy, causing PostgreSQL error 42P17.
-- Fix: check user_id directly on the current row.
-- ============================================================

DROP POLICY IF EXISTS "Members can view org members" ON public.org_members;

-- Use auth.uid() directly (not wrapped in select) to avoid PostgreSQL
-- detecting infinite recursion on this self-referencing policy.
-- This matches the original working pattern from 001_initial_schema.sql.
CREATE POLICY "Members can view org members" ON public.org_members
  FOR SELECT TO authenticated
  USING (
    EXISTS (
      SELECT 1 FROM public.org_members om
      WHERE om.org_id = org_members.org_id
        AND om.user_id = auth.uid()
    )
  );

-- Also fix the UPDATE and DELETE policies which have the same self-reference
DROP POLICY IF EXISTS "Owners and admins can manage members" ON public.org_members;
CREATE POLICY "Owners and admins can manage members" ON public.org_members
  FOR UPDATE TO authenticated
  USING (
    EXISTS (
      SELECT 1 FROM public.org_members om2
      WHERE om2.org_id = org_members.org_id
        AND om2.user_id = auth.uid()
        AND om2.role IN ('owner', 'admin')
    )
  )
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.org_members om2
      WHERE om2.org_id = org_members.org_id
        AND om2.user_id = auth.uid()
        AND om2.role IN ('owner', 'admin')
    )
  );

DROP POLICY IF EXISTS "Owners and admins can delete members" ON public.org_members;
CREATE POLICY "Owners and admins can delete members" ON public.org_members
  FOR DELETE TO authenticated
  USING (
    EXISTS (
      SELECT 1 FROM public.org_members om2
      WHERE om2.org_id = org_members.org_id
        AND om2.user_id = auth.uid()
        AND om2.role IN ('owner', 'admin')
    )
  );

DROP POLICY IF EXISTS "Allow member inserts" ON public.org_members;
CREATE POLICY "Allow member inserts" ON public.org_members
  FOR INSERT TO authenticated
  WITH CHECK (
    EXISTS (
      SELECT 1 FROM public.org_members om
      WHERE om.org_id = org_members.org_id
        AND om.user_id = auth.uid()
        AND om.role IN ('owner', 'admin')
    )
    OR org_members.user_id = auth.uid()
  );
