import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvoiceCancellationBlockedError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { baseSalesInvoice, issuedSalesInvoice } from "../testing/fixtures";
import { run } from "./cancelSalesInvoice";

describe("cancelSalesInvoice", () => {
  it("cancels a draft invoice", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseSalesInvoice],
      [
        {
          ...baseSalesInvoice,
          status: "CANCELLED",
          updatedAt: new Date(),
        },
      ],
    );

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

    const value = expectOk(result);
    expect(value.salesInvoice.status).toBe("CANCELLED");
  });

  it("cancels an issued invoice before AR handoff", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [issuedSalesInvoice],
      [
        {
          ...issuedSalesInvoice,
          status: "CANCELLED",
          updatedAt: new Date(),
        },
      ],
    );

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

    expectOk(result);
  });

  it("throws when AR handoff already accepted the invoice", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...issuedSalesInvoice, arHandoffAccepted: true }]);

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

    expectErr(result, InvoiceCancellationBlockedError);
  });
});
