import { describe, expect, it } from "vitest";
import { createMockDb, testNotFound, testIdempotent } from "../../../testing/index";
import { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    const activatedCurrency = {
      ...inactiveCurrency,
      isActive: true,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select.mockReturnValue(inactiveCurrency);
    spies.update.mockReturnValue(activatedCurrency);

    const result = await run(db, {
      currencyId: inactiveCurrency.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.currency.isActive).toBe(true);
      expect(result.value.currency.updatedAt).not.toBeNull();
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
