import { describe, expect, it } from "vitest";
import { createMockDb, testNotFound, testIdempotent } from "../../../testing/index";
import { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(baseCurrencyUSD); // USD is base currency

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    const deactivatedCurrency = {
      ...baseCurrencyEUR,
      isActive: false,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select.mockReturnValue(baseCurrencyEUR); // EUR is not base currency
    spies.update.mockReturnValue(deactivatedCurrency);

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

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