import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  InvalidPaymentScheduleError,
  InvalidSalespaymenttermStatusError,
  SalespaymenttermNotFoundError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { basePaymentTerm, draftPaymentTerm } from "../testing/fixtures";
import { run } from "./activateSalesPaymentTerm";

describe("activateSalesPaymentTerm", () => {
  it("activates a draft SalesPaymentTerm", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activated = {
      ...draftPaymentTerm,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([draftPaymentTerm], [activated]);

    const result = await mock.withTx((trx) =>
      run(trx, { salesPaymentTermId: draftPaymentTerm.id }, commandCtx),
    );

    expectOk(result);
  });

  it("throws when SalesPaymentTerm is not in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePaymentTerm]);

    const result = await mock.withTx((trx) =>
      run(trx, { salesPaymentTermId: basePaymentTerm.id }, commandCtx),
    );

    expectErr(result, InvalidSalespaymenttermStatusError);
  });

  it("throws when SalesPaymentTerm does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { salesPaymentTermId: draftPaymentTerm.id }, commandCtx),
    );

    expectErr(result, SalespaymenttermNotFoundError);
  });

  it("throws on invalid payment schedule", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([
      {
        ...draftPaymentTerm,
        scheduleLines: JSON.stringify([{ kind: "INSTALLMENT", days: 15, percentage: 80 }]),
      },
    ]);

    const result = await mock.withTx((trx) =>
      run(trx, { salesPaymentTermId: draftPaymentTerm.id }, commandCtx),
    );

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