import { describe, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidPaymentScheduleError,
  InvalidSalespaymenttermStatusError,
  SalespaymenttermNotFoundError,
} from "../lib/errors.generated";
import { basePaymentTerm, draftPaymentTerm } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./activateSalesPaymentTerm";

describe("activateSalesPaymentTerm", () => {
  it("activates a draft SalesPaymentTerm", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activated = {
      ...draftPaymentTerm,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(draftPaymentTerm);
    spies.update.mockReturnValueOnce(activated);

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

    expectOk(result);
  });

  it("throws when SalesPaymentTerm is not in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);

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

    expectErr(result, InvalidSalespaymenttermStatusError);
  });

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

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

    expectErr(result, SalespaymenttermNotFoundError);
  });

  it("throws on invalid payment schedule", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({
      ...draftPaymentTerm,
      scheduleLines: JSON.stringify([{ kind: "INSTALLMENT", days: 15, percentage: 80 }]),
    });

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

    expectErr(result, InvalidPaymentScheduleError);
  });
});
