import { getApiFieldErrors } from "@/lib/api/errors";

const COMMON_ALIASES: Record<string, string> = {
  date_of_birth: "dob", residency_status: "nationality", title_en: "title_ar", description_en: "description_ar",
  participants_needed: "participantsNeeded", start_date: "startDate", end_date: "endDate", start_time: "startTime", end_time: "endTime",
  from_age: "age", to_age: "age", registration_deadline_hours: "registrationDeadlineHours", learning_type_id: "learningType",
  format_id: "learnServeFormat", certificate_type_id: "certificateType", volunteer_category: "volunteerCategory",
  beneficiaries_count: "beneficiariesCount", interest_ids: "_interests", is_public: "isPrivate", gender_id: "gender",
  event_type_id: "event_type", participation_type_id: "participation_type", whatsapp_link: "whatsappLink",
};

/** Attach server errors to visible fields, including legacy API names and array keys. */
export function mapFormApiErrors(error: unknown, language: string, fields: readonly string[], aliases: Record<string, string> = {}): Record<string, string> {
  const result: Record<string, string> = {};
  for (const [raw, message] of Object.entries(getApiFieldErrors(error, language))) {
    const base = raw.split(/[.\[]/, 1)[0];
    const target = aliases[base] ?? (base === "title_en" || base === "description_en" ? COMMON_ALIASES[base] : fields.includes(base) ? base : COMMON_ALIASES[base]);
    if (!target || !fields.includes(target)) continue;
    result[target] = result[target] ? `${result[target]} · ${message}` : message;
  }
  return result;
}

export function applyFormApiErrors(error: unknown, language: string, fields: readonly string[], setFieldError: (field: string, message: string) => void, aliases?: Record<string, string>): void {
  for (const [field, message] of Object.entries(mapFormApiErrors(error, language, fields, aliases))) setFieldError(field, message);
}
