import assert from "node:assert/strict";
import test from "node:test";

import { isLocaleChunkLoadError, loadLocaleModuleWithRetry } from "../src/i18n/index.ts";

test("i18n locale loader retries transient dynamic import failures", async () => {
  let calls = 0;
  const waits: number[] = [];

  const result = await loadLocaleModuleWithRetry(
    async () => {
      calls += 1;
      if (calls < 3) throw new Error("Failed to fetch dynamically imported module: https://hwlab.pikapython.com/assets/en.js");
      return { default: { nav: { dashboard: "Dashboard" } } };
    },
    [1, 2],
    async (ms) => {
      waits.push(ms);
    }
  );

  assert.equal(result.attempts, 3);
  assert.equal(calls, 3);
  assert.deepEqual(waits, [1, 2]);
  assert.deepEqual(result.module.default, { nav: { dashboard: "Dashboard" } });
});

test("i18n chunk error classifier covers Vite dynamic import failures", () => {
  assert.equal(isLocaleChunkLoadError(new Error("Failed to fetch dynamically imported module: https://hwlab.pikapython.com/assets/en.js")), true);
  assert.equal(isLocaleChunkLoadError(new Error("Importing a module script failed.")), true);
  assert.equal(isLocaleChunkLoadError(new Error("ordinary locale parse error")), false);
});
