/**
 * `getLocalizedApiMessage` has to behave exactly like the fifteen hand-written
 * `` error.response.data[`message_${language}`] || fallback `` expressions it
 * replaces, including for the shapes those expressions handled by accident:
 * a thrown axios error, an already-unwrapped body, and a body that carries
 * `msg` or `validation_errors` instead of the localized pair.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";

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

const axiosError = (body: unknown) => ({ response: { data: body } });

describe("getLocalizedApiMessage", () => {
  test("picks message_en for English", () => {
    assert.equal(
      getLocalizedApiMessage(
        axiosError({ message_en: "Not allowed", message_ar: "غير مسموح" }),
        "en",
        "fallback"
      ),
      "Not allowed"
    );
  });

  test("picks message_ar for Arabic", () => {
    assert.equal(
      getLocalizedApiMessage(
        axiosError({ message_en: "Not allowed", message_ar: "غير مسموح" }),
        "ar",
        "fallback"
      ),
      "غير مسموح"
    );
  });

  test("reads an already-unwrapped body, not just a thrown axios error", () => {
    assert.equal(
      getLocalizedApiMessage({ message_en: "Direct" }, "en", "fallback"),
      "Direct"
    );
  });

  test("an empty string is not a message — the fallback wins", () => {
    assert.equal(
      getLocalizedApiMessage(axiosError({ message_en: "" }), "en", "fallback"),
      "fallback"
    );
  });

  test("falls through to msg when the localized pair is absent", () => {
    assert.equal(
      getLocalizedApiMessage(axiosError({ msg: "Validation error" }), "en", "fallback"),
      "Validation error"
    );
  });

  test("falls through to a field error before msg, as the generic path does", () => {
    assert.equal(
      getLocalizedApiMessage(
        axiosError({
          msg: "Validation error",
          response_status: { validation_errors: { civil_id: ["Already used"] } },
        }),
        "en",
        "fallback"
      ),
      "Already used"
    );
  });

  test("the fallback is used for a network error with no body at all", () => {
    assert.equal(getLocalizedApiMessage(new Error("offline"), "en", "fallback"), "fallback");
    assert.equal(getLocalizedApiMessage(undefined, "en", "fallback"), "fallback");
    assert.equal(getLocalizedApiMessage(null, "en", "fallback"), "fallback");
  });

  test("an unknown language falls back to the English message, not to the fallback", () => {
    assert.equal(
      getLocalizedApiMessage(axiosError({ message_en: "English only" }), "fr", "fallback"),
      "English only"
    );
  });
});
