import { describe, expect, it, vi } from "vitest";
import { createLocaleManager } from "./localization";

const pluginInfo = { pluginId: "testPlugin" };

// Mock data
const translations = {
  en: { testPlugin: { hello: "Hello" } },
  es: { testPlugin: { hello: "Hola" } },
};

describe("createLocaleManager", () => {
  it("should return an object with translate, getTranslations, and getCurrentLanguage functions", async () => {
    const localeManager = await createLocaleManager(pluginInfo.pluginId)(translations as any);
    expect(localeManager).toHaveProperty("translate");
    expect(localeManager).toHaveProperty("getTranslations");
    expect(localeManager).toHaveProperty("getCurrentLanguage");
  });

  it("should translate a given path using localizer", async () => {
    const localeManager = await createLocaleManager(pluginInfo.pluginId)(translations as any);
    const result = localeManager.translate("hello");
    expect(result).toBe("Hello");
  });

  it("should return the full path if no exist translation for given path", async () => {
    const localeManager = await createLocaleManager(pluginInfo.pluginId)(translations as any);
    const result = localeManager.translate("hellaaa");
    expect(result).toBe("testPlugin.hellaaa");
  });

  it("should return the path if there is an error translating", async () => {
    const localeManager = await createLocaleManager(pluginInfo.pluginId)(translations as any);
    const translateSpy = vi.spyOn(localeManager, "translate").mockImplementation(() => {
      throw new Error("mocked error");
    });

    let result;
    try {
      result = localeManager.translate("hello");
    } catch (error) {
      result = "hello";
    }

    expect(result).toBe("hello");
    // Restore the original implementation
    translateSpy.mockRestore();
  });

  it("should get translations for the current language", async () => {
    const localeManager = await createLocaleManager(pluginInfo.pluginId)(translations);
    const result = localeManager.getTranslations();
    expect(result).toEqual(translations.en.testPlugin);
  });

  it("should get the current language", async () => {
    const localeManager = await createLocaleManager(pluginInfo.pluginId)(translations);
    const result = localeManager.getCurrentLanguage();
    expect(result).toBe("en");
  });
});
