import { getApiFieldErrors, getApiErrorMessages } from "@/lib/api/errors";
import { applyFormApiErrors, mapFormApiErrors } from "@/features/shared/formApiErrors";

/**
 * `applyFormApiErrors`, plus what is left over for a toast (PDF p.37: a field's
 * error belongs next to the field). Field errors land on the form; only the
 * messages no visible field can carry — and the plain `msg` of a failure with
 * no field detail — come back in `rest`. `mapped` is how many fields received
 * an error, so a caller can tell "all shown inline" from "the API said
 * nothing" and toast its generic fallback only in the second case.
 */
export function splitFormApiErrors(
  error: unknown,
  language: string,
  fields: readonly string[],
  setFieldError: (field: string, message: string) => void,
  aliases?: Record<string, string>
): { mapped: number; rest: string[] } {
  const mapped = Object.keys(mapFormApiErrors(error, language, fields, aliases)).length;
  applyFormApiErrors(error, language, fields, setFieldError, aliases);

  const fieldErrors = Object.entries(getApiFieldErrors(error, language));
  if (fieldErrors.length === 0) return { mapped, rest: getApiErrorMessages(error, language) };

  const rest = fieldErrors
    .filter(([field, message]) => {
      const single = { response_status: { validation_errors: { [field]: [message] } } };
      return Object.keys(mapFormApiErrors(single, language, fields, aliases)).length === 0;
    })
    .map(([, message]) => message);
  return { mapped, rest };
}
