import { afterEach, describe, expect, it } from "vitest";
import { createI18nInstance } from "./config.js";
import { serializeI18nForHydration, hydrateI18nFromWindow } from "./serializer.js";

describe("serializeI18nForHydration", () => {
  it("returns a JSON string containing locale and resources", async () => {
    const i18n = await createI18nInstance({ locale: "ru" });
    const json = serializeI18nForHydration(i18n);
    const parsed = JSON.parse(json);
    expect(parsed.locale).toBe("ru");
    expect(parsed.resources).toBeDefined();
    expect(parsed.resources.common).toBeDefined();
    expect(parsed.resources.common["BOARD"]).toBeDefined();
  });
});

describe("hydrateI18nFromWindow", () => {
  afterEach(() => {
    // Clean up the global
    if (typeof globalThis !== "undefined") {
      delete (globalThis as Record<string, unknown>).__I18N__;
    }
  });

  it("roundtrips: serialize → inject into globalThis.__I18N__ → hydrate", async () => {
    const original = await createI18nInstance({ locale: "ru" });
    const json = serializeI18nForHydration(original);
    const payload = JSON.parse(json);

    // Simulate the SSR injection into the global scope
    (globalThis as Record<string, unknown>).__I18N__ = payload;

    const hydrated = await hydrateI18nFromWindow();
    expect(hydrated.language).toBe("ru");
    expect(hydrated.t("BOARD.DEPARTURE")).toBe(original.t("BOARD.DEPARTURE"));
  });

  it("throws if __I18N__ is not set", async () => {
    await expect(hydrateI18nFromWindow()).rejects.toThrow(/__I18N__/);
  });
});
