
-- Restrict board members to only their assigned bill_approvals
DROP POLICY IF EXISTS "Board members can view association bill_approvals" ON public.bill_approvals;

CREATE POLICY "Board members view assigned bill_approvals"
  ON public.bill_approvals FOR SELECT
  USING (
    EXISTS (
      SELECT 1 FROM public.board_members bm
      WHERE bm.user_id = auth.uid()
        AND bm.association_id = bill_approvals.association_id
        AND bm.member_name = bill_approvals.vendor_name
    )
  );

-- Restrict board members to only bills that have a bill_approval assigned to them
DROP POLICY IF EXISTS "Board members can view association bills" ON public.bills;

CREATE POLICY "Board members view bills assigned to them"
  ON public.bills FOR SELECT
  USING (
    EXISTS (
      SELECT 1
      FROM public.bill_approvals ba
      JOIN public.board_members bm
        ON bm.association_id = ba.association_id
       AND bm.member_name = ba.vendor_name
       AND bm.user_id = auth.uid()
      WHERE ba.bill_id = bills.id
    )
  );
