import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  SalespaymenttermNotEditableError,
  SalespaymenttermNotFoundError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  basePaymentTerm,
  inactivePaymentTerm,
  installmentScheduleLines,
} from "../testing/fixtures";
import { run } from "./updateSalesPaymentTerm";

describe("updateSalesPaymentTerm", () => {
  it("updates mutable SalesPaymentTerm fields", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [basePaymentTerm],
      [
        {
          ...basePaymentTerm,
          name: "Installments",
          scheduleLines: JSON.stringify(installmentScheduleLines),
          updatedAt: new Date(),
        },
      ],
    );

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

    expectOk(result);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ name: "Installments" }),
    );
  });

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

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

    expectErr(result, SalespaymenttermNotFoundError);
  });

  it("returns error when SalesPaymentTerm is not editable", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactivePaymentTerm]);

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

    expectErr(result, SalespaymenttermNotEditableError);
  });
});
