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

describe("updateSalesPaymentTerm", () => {
  it("updates mutable SalesPaymentTerm fields", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePaymentTerm);
    spies.update.mockReturnValueOnce({
      ...basePaymentTerm,
      name: "Installments",
      scheduleLines: JSON.stringify(installmentScheduleLines),
      updatedAt: new Date(),
    });

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

    expectOk(result);
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ name: "Installments" }));
  });

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

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

    expectErr(result, SalespaymenttermNotFoundError);
  });

  it("returns error when SalesPaymentTerm is not editable", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactivePaymentTerm);

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

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