DROP POLICY IF EXISTS "Board members can view bill_approvals" ON public.bill_approvals;
DROP POLICY IF EXISTS "Board members can update bill_approvals" ON public.bill_approvals;

CREATE POLICY "Assigned approvers can view bills"
ON public.bills
FOR SELECT
TO authenticated
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
    WHERE ba.bill_id = public.bills.id
      AND bm.user_id = auth.uid()
      AND bm.approval_authority = true
  )
);

CREATE POLICY "Assigned approvers can view bill_approvals"
ON public.bill_approvals
FOR SELECT
TO authenticated
USING (
  EXISTS (
    SELECT 1
    FROM public.board_members bm
    WHERE bm.association_id = public.bill_approvals.association_id
      AND bm.member_name = public.bill_approvals.vendor_name
      AND bm.user_id = auth.uid()
      AND bm.approval_authority = true
  )
);

CREATE POLICY "Assigned approvers can update bill_approvals"
ON public.bill_approvals
FOR UPDATE
TO authenticated
USING (
  EXISTS (
    SELECT 1
    FROM public.board_members bm
    WHERE bm.association_id = public.bill_approvals.association_id
      AND bm.member_name = public.bill_approvals.vendor_name
      AND bm.user_id = auth.uid()
      AND bm.approval_authority = true
  )
)
WITH CHECK (
  EXISTS (
    SELECT 1
    FROM public.board_members bm
    WHERE bm.association_id = public.bill_approvals.association_id
      AND bm.member_name = public.bill_approvals.vendor_name
      AND bm.user_id = auth.uid()
      AND bm.approval_authority = true
  )
);