DROP FUNCTION IF EXISTS public.verify_board_invoice_insert_policy(uuid, uuid);

CREATE FUNCTION public.verify_board_invoice_insert_policy(_user_id uuid, _association_id uuid)
RETURNS jsonb
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 jsonb_build_object('ok', false, 'reason', 'not_board_member_for_association');
  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 jsonb_build_object('ok', true);
EXCEPTION WHEN OTHERS THEN
  RETURN jsonb_build_object('ok', false, 'reason', SQLERRM, 'state', SQLSTATE);
END;
$$;

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