import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvoiceCancellationBlockedError } from "../lib/errors.generated";
import { baseSalesInvoice, issuedSalesInvoice } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelSalesInvoice";

describe("cancelSalesInvoice", () => {
  it("cancels a draft invoice", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSalesInvoice);
    spies.update.mockReturnValueOnce({
      ...baseSalesInvoice,
      status: "CANCELLED",
      updatedAt: new Date(),
    });

    const result = await run(db, { salesInvoiceId: baseSalesInvoice.id }, commandCtx);

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

  it("cancels an issued invoice before AR handoff", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(issuedSalesInvoice);
    spies.update.mockReturnValueOnce({
      ...issuedSalesInvoice,
      status: "CANCELLED",
      updatedAt: new Date(),
    });

    const result = await run(db, { salesInvoiceId: issuedSalesInvoice.id }, commandCtx);

    expectOk(result);
  });

  it("throws when AR handoff already accepted the invoice", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...issuedSalesInvoice, arHandoffAccepted: true });

    const result = await run(db, { salesInvoiceId: issuedSalesInvoice.id }, commandCtx);

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