import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { testNotFound, testIdempotent } from "../../../testing";
import type { Namespace } from "../generated/kysely-tailordb";
import { CurrencyNotFoundError } from "../lib/errors.generated";
import { baseCurrencyUSD, inactiveCurrency } from "../testing/fixtures";
import { run } from "./activateCurrency";

describe("activateCurrency", () => {
  it(
    "throws when currency doesn't exist",
    testNotFound(run, { currencyId: "nonexistent-currency" }, CurrencyNotFoundError),
  );

  it(
    "returns currency unchanged when already active",
    testIdempotent(run, { currencyId: baseCurrencyUSD.id }, baseCurrencyUSD, "currency"),
  );

  // Success cases
  it("activates inactive currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activatedCurrency = {
      ...inactiveCurrency,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults([inactiveCurrency], [activatedCurrency]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        currencyId: inactiveCurrency.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.currency.status).toBe("ACTIVE");
      expect(result.value.currency.updatedAt).not.toBeNull();
    }
    expect(mock.updates).toHaveLength(1);
  });
});
