CREATE OR REPLACE FUNCTION public.get_required_approvals_for_bill(p_bill_id uuid)
 RETURNS integer
 LANGUAGE plpgsql
 STABLE SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  v_assoc uuid;
  v_amount numeric;
  v_vendor text;
  v_rule public.bill_approval_rules%ROWTYPE;
  v_required integer;
BEGIN
  SELECT b.association_id, b.amount, COALESCE(v.name, b.notes, '')
  INTO v_assoc, v_amount, v_vendor
  FROM public.bills b
  LEFT JOIN public.vendors v ON v.id = b.vendor_id
  WHERE b.id = p_bill_id;

  IF v_assoc IS NULL THEN RETURN NULL; END IF;

  SELECT * INTO v_rule FROM public.bill_approval_rules WHERE association_id = v_assoc;
  IF v_rule.id IS NULL OR v_rule.enabled = false THEN
    RETURN NULL;
  END IF;

  SELECT required_approvals INTO v_required
  FROM public.bill_approval_rule_vendor_exceptions
  WHERE rule_id = v_rule.id AND lower(vendor_name) = lower(v_vendor)
  LIMIT 1;
  IF v_required IS NOT NULL THEN RETURN v_required; END IF;

  SELECT required_approvals INTO v_required
  FROM public.bill_approval_rule_thresholds
  WHERE rule_id = v_rule.id
    AND COALESCE(v_amount,0) >= min_amount
    AND (max_amount IS NULL OR COALESCE(v_amount,0) <= max_amount)
  ORDER BY min_amount DESC
  LIMIT 1;
  IF v_required IS NOT NULL THEN RETURN v_required; END IF;

  RETURN v_rule.required_approvals;
END;
$function$;