import { expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
  createLocaleFormatter,
  formatMessage,
  loadRouteMessages,
  resolveI18n,
  withTenantMessages,
} from "../src/index.ts";

test("formats ICU plural, exact and gender-aware select messages", () => {
  expect(
    formatMessage("{count, plural, =0 {None} one {# item} other {# items}}", { count: 2 }, "en"),
  ).toBe("2 items");
  expect(
    formatMessage(
      "{gender, select, female {She} male {He} other {They}} approved",
      { gender: "female" },
      "en",
    ),
  ).toBe("She approved");
});
test("supports calendars, tenant overrides and route-scoped loading", () => {
  const formatter = createLocaleFormatter("en-US", "UTC", "indian");
  expect(
    formatter.date(new Date("2026-08-02T00:00:00Z"), { year: "numeric", calendar: "indian" }),
  ).toBeTruthy();
  const base = resolveI18n({ en: { title: "Default" } }, { default: "en" });
  expect(withTenantMessages(base, { en: { title: "Tenant" } }).messages.en?.title).toBe("Tenant");
  expect(base.messages.en?.title).toBe("Default");
  const root = mkdtempSync(join(tmpdir(), "wrnexus-i18n-route-"));
  mkdirSync(join(root, "en/routes/users"), { recursive: true });
  writeFileSync(join(root, "en/common.json"), JSON.stringify({ common: "Common" }));
  writeFileSync(join(root, "en/routes/users/index.json"), JSON.stringify({ title: "Users" }));
  expect(loadRouteMessages(root, "en", "/users/index")).toEqual({
    common: "Common",
    title: "Users",
  });
});
