import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { baseCurrencyUSD } from "../testing/fixtures";
import { run } from "./getCurrency";

describe("getCurrency", () => {
  describe("by id", () => {
    it("returns currency when found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([baseCurrencyUSD]);

      const result = await run(mock.db, { id: "currency-usd" });

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.currency).toEqual(baseCurrencyUSD);
      }
      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0].parameters).toContain("currency-usd");
      expect(mock.selects[0].sql).toMatch(/"id"/);
    });

    it("returns null when currency not found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([]);

      const result = await run(mock.db, { id: "nonexistent" });

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.currency).toBeNull();
      }
    });
  });

  describe("by code", () => {
    it("returns currency when found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([baseCurrencyUSD]);

      const result = await run(mock.db, { code: "USD" });

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.currency).toEqual(baseCurrencyUSD);
      }
      expect(mock.selects).toHaveLength(1);
      expect(mock.selects[0].parameters).toContain("USD");
      expect(mock.selects[0].sql).toMatch(/"code"/);
    });

    it("returns null when currency not found", async () => {
      const mock = createKyselyMock<Namespace["main-db"]>();
      mock.enqueueResults([]);

      const result = await run(mock.db, { code: "NONEXISTENT" });

      expect(result.ok).toBe(true);
      if (result.ok) {
        expect(result.value.currency).toBeNull();
      }
    });
  });
});
