import { toast } from "sonner";

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

/**
 * What to tell the user when a write is refused: whatever the API said, or the
 * caller's generic message when it said nothing.
 *
 * Split from the toasting so the decision can be tested without mocking the
 * toast library — `apiErrorMessages` is a pure function of the rejection.
 *
 * 111 call sites already made this choice by hand; 32 others discarded the
 * response and showed only their own string. That is not cosmetic: the backend
 * is the only party that knows *why* a write failed, and several of those 32
 * call endpoints behind `EnsureOrganizationApproved`, which answers 403 with
 * "Your organization account has not been approved by the admin yet."
 * Replacing that with "Upload failed" tells the organizer nothing actionable.
 *
 * Messages arrive already localized by the backend from the language header, so
 * there is nothing to pick per language here — `language` only selects between
 * the two sides of the older `{ en, ar }` field-error shape that
 * `getApiErrorMessages` still handles.
 */
export function apiErrorMessages(
  error: unknown,
  language: string,
  fallback: string
): string[] {
  const messages = getApiErrorMessages(error, language);
  return messages.length > 0 ? messages : [fallback];
}

/**
 * The same choice, shown as toasts.
 *
 * `fallback` is passed already translated, because `t` belongs to the calling
 * component and a key resolved here would miss its namespace.
 */
export function toastApiError(
  error: unknown,
  language: string,
  fallback: string
): void {
  apiErrorMessages(error, language, fallback).forEach((message) =>
    toast.error(message)
  );
}
