import { CurrencyManager } from "@/lib/utils/currency";

describe("CurrencyManager", () => {
  describe("detectUserCurrency", () => {
    it("should detect SAR for Riyadh timezone", () => {
      jest
        .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions")
        .mockReturnValue({
          timeZone: "Asia/Riyadh",
        } as any);

      expect(CurrencyManager.detectUserCurrency()).toBe("SAR");
    });

    it("should detect AED for Dubai timezone", () => {
      jest
        .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions")
        .mockReturnValue({
          timeZone: "Asia/Dubai",
        } as any);

      expect(CurrencyManager.detectUserCurrency()).toBe("AED");
    });

    it("should default to GBP for unknown timezone", () => {
      jest
        .spyOn(Intl.DateTimeFormat.prototype, "resolvedOptions")
        .mockReturnValue({
          timeZone: "Unknown/Zone",
        } as any);

      expect(CurrencyManager.detectUserCurrency()).toBe("GBP");
    });
  });

  describe("convert", () => {
    it("should convert GBP to USD correctly", () => {
      const result = CurrencyManager.convert(100, "USD");
      expect(result).toBe(127); // 100 * 1.27
    });

    it("should return same value for GBP to GBP", () => {
      const result = CurrencyManager.convert(100, "GBP");
      expect(result).toBe(100);
    });

    it("should handle invalid currency gracefully", () => {
      const result = CurrencyManager.convert(100, "XXX" as any);
      expect(result).toBe(100); // fallback to rate 1
    });
  });

  describe("formatPrice", () => {
    it("should format price with symbol and locale", () => {
      const result = CurrencyManager.formatPrice(1234, "USD");
      expect(result).toContain("$");
      expect(result).toContain("1,234");
    });
  });

  describe("findStripePrice", () => {
    it("should find matching price by currency and interval", () => {
      const prices = [
        { id: "price_1", currency: "usd", interval: "month", unitAmount: 1000 },
        { id: "price_2", currency: "gbp", interval: "month", unitAmount: 800 },
      ] as any;

      const result = CurrencyManager.findStripePrice(prices, "USD", "month");
      expect(result?.id).toBe("price_1");
    });

    it("should return undefined when no match found", () => {
      const prices = [] as any;
      const result = CurrencyManager.findStripePrice(prices, "USD", "month");
      expect(result).toBeUndefined();
    });
  });
});
