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 { CannotDeactivateBaseCurrencyError, CurrencyNotFoundError } from "../lib/errors.generated";
import { baseCurrencyEUR, baseCurrencyUSD, inactiveCurrency } from "../testing/fixtures";
import { run } from "./deactivateCurrency";

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

  it("throws when attempting to deactivate base currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseCurrencyUSD]); // USD is base currency

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CannotDeactivateBaseCurrencyError);
    }
  });

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

  // Success cases
  it("deactivates active non-base currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedCurrency = {
      ...baseCurrencyEUR,
      status: "INACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults([baseCurrencyEUR], [deactivatedCurrency]); // EUR is not base currency

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

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