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

describe("createSalesPaymentTerm", () => {
  it("creates a payment term with valid schedule lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany);
    spies.insert.mockReturnValueOnce(draftPaymentTerm);

    const result = await run(
      db,
      { companyId: baseCompany.id, name: basePaymentTerm.name, scheduleLines: baseScheduleLines },
      commandCtx,
    );

    expectOk(result);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ status: "DRAFT", companyId: baseCompany.id }),
    );
  });

  it("throws when required SalesPaymentTerm fields are missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany);

    const result = await run(
      db,
      { companyId: baseCompany.id, name: basePaymentTerm.name, scheduleLines: [] },
      commandCtx,
    );

    expectErr(result, InvalidPaymentScheduleError);
  });

  it("creates the SalesPaymentTerm in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany);
    spies.insert.mockReturnValueOnce(draftPaymentTerm);

    const result = await run(
      db,
      { companyId: baseCompany.id, name: basePaymentTerm.name, scheduleLines: baseScheduleLines },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.salesPaymentTerm.status).toBe("DRAFT");
  });
});
