CREATE OR REPLACE FUNCTION public.is_board_member_of_association(_user_id uuid, _association_id uuid)
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = public
AS $$
  SELECT EXISTS (
    SELECT 1
    FROM public.board_members bm
    WHERE bm.user_id = _user_id
      AND bm.association_id = _association_id
  )
$$;

DROP POLICY IF EXISTS "Board members can insert invoices for their associations" ON public.invoices;
CREATE POLICY "Board members can insert invoices for their associations"
ON public.invoices
FOR INSERT
TO authenticated
WITH CHECK (
  public.is_board_member_of_association(auth.uid(), association_id)
);

DROP POLICY IF EXISTS "Board members can view invoices for their associations" ON public.invoices;
CREATE POLICY "Board members can view invoices for their associations"
ON public.invoices
FOR SELECT
TO authenticated
USING (
  public.is_board_member_of_association(auth.uid(), association_id)
);

DROP POLICY IF EXISTS "Board members can insert bills for their associations" ON public.bills;
CREATE POLICY "Board members can insert bills for their associations"
ON public.bills
FOR INSERT
TO authenticated
WITH CHECK (
  public.is_board_member_of_association(auth.uid(), association_id)
);
