CREATE OR REPLACE FUNCTION public.verify_board_invoice_insert_policy(_user_id uuid, _association_id uuid)
RETURNS boolean
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
  v_inserted_id uuid;
BEGIN
  IF NOT public.is_board_member_of_association(_user_id, _association_id) THEN
    RETURN false;
  END IF;

  INSERT INTO public.invoices (
    association_id,
    vendor_name,
    invoice_number,
    amount,
    status,
    issue_date,
    due_date,
    description,
    created_by,
    raw_pdf_url,
    line_items
  ) VALUES (
    _association_id,
    'RLS Verification Vendor',
    'RLS-VERIFY-' || to_char(clock_timestamp(), 'YYYYMMDDHH24MISSMS'),
    1.23,
    'pending',
    CURRENT_DATE,
    CURRENT_DATE,
    'Automatic RLS verification test',
    _user_id,
    'https://example.com/rls-verification.pdf',
    '[]'::jsonb
  )
  RETURNING id INTO v_inserted_id;

  DELETE FROM public.invoices WHERE id = v_inserted_id;
  RETURN true;
EXCEPTION WHEN OTHERS THEN
  RETURN false;
END;
$$;

GRANT EXECUTE ON FUNCTION public.verify_board_invoice_insert_policy(uuid, uuid) TO authenticated;
