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

describe("activatePurchasePaymentTerm", () => {
  it("activates an inactive payment term", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePaymentTerm);
    spies.update.mockReturnValueOnce({ ...inactivePaymentTerm, status: "ACTIVE" });

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

    expect(value.purchasePaymentTerm.status).toBe("ACTIVE");
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ status: "ACTIVE" }));
  });

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

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

    expect(value.purchasePaymentTerm).toEqual(basePaymentTerm);
    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 the payment term schedule is invalid at activation time", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({
      ...inactivePaymentTerm,
      scheduleLines: JSON.stringify([{ kind: "INSTALLMENT", days: 30, percentage: 80 }]),
    });

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

    expectErr(result, InvalidTermConfigurationError);
  });
});
