import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidPaymentScheduleError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseCompany,
  basePaymentTerm,
  baseScheduleLines,
  draftPaymentTerm,
} from "../testing/fixtures";
import { mockOrgQueries } from "../testing/moduleMocks";
import { run } from "./createSalesPaymentTerm";

describe("createSalesPaymentTerm", () => {
  it("creates a payment term with valid schedule lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPaymentTerm]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseCompany.id, name: basePaymentTerm.name, scheduleLines: baseScheduleLines },
        commandCtx,
        mockOrgQueries(baseCompany),
      ),
    );

    expectOk(result);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ status: "DRAFT", companyId: baseCompany.id }),
    );
  });

  it("throws when required SalesPaymentTerm fields are missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseCompany.id, name: basePaymentTerm.name, scheduleLines: [] },
        commandCtx,
        mockOrgQueries(baseCompany),
      ),
    );

    expectErr(result, InvalidPaymentScheduleError);
  });

  it("creates the SalesPaymentTerm in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([draftPaymentTerm]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseCompany.id, name: basePaymentTerm.name, scheduleLines: baseScheduleLines },
        commandCtx,
        mockOrgQueries(baseCompany),
      ),
    );

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