import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { PaymentTermInUseError, PaymentTermNotFoundError } from "../lib/errors.generated";
import { baseSupplierProfile, basePaymentTerm, inactivePaymentTerm } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./deactivatePurchasePaymentTerm";

describe("deactivatePurchasePaymentTerm", () => {
  it("deactivates an active payment term", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm).mockReturnValueOnce(undefined);
    spies.update.mockReturnValueOnce({ ...basePaymentTerm, status: "INACTIVE" });

    const result = await run(db, { id: basePaymentTerm.id }, commandCtx);
    const value = expectOk<{ purchasePaymentTerm: typeof basePaymentTerm }>(result);

    expect(value.purchasePaymentTerm.status).toBe("INACTIVE");
  });

  it("returns success when the payment term is already inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePaymentTerm);

    const result = await run(db, { id: inactivePaymentTerm.id }, commandCtx);
    const value = expectOk<{ purchasePaymentTerm: typeof inactivePaymentTerm }>(result);

    expect(value.purchasePaymentTerm).toEqual(inactivePaymentTerm);
    expect(spies.update).not.toHaveBeenCalled();
  });

  it("returns error when payment term does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "missing-term" }, commandCtx);

    expectErr(result, PaymentTermNotFoundError);
  });

  it("returns error when payment term is still configured as a supplier default", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm).mockReturnValueOnce(baseSupplierProfile);

    const result = await run(db, { id: basePaymentTerm.id }, commandCtx);

    expectErr(result, PaymentTermInUseError);
  });
});
