import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CancellationBlockedError } from "../lib/errors.generated";
import {
  baseSalesInvoice,
  baseSalesOrder,
  confirmedSalesOrder,
  postedShipment,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelSalesOrder";

describe("cancelSalesOrder", () => {
  it("cancels a draft order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = {
      ...baseSalesOrder,
      status: "CANCELLED",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select
      .mockReturnValueOnce(baseSalesOrder)
      .mockReturnValueOnce([])
      .mockReturnValueOnce([]);
    spies.update.mockReturnValueOnce(cancelled);

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

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

  it("cancels a confirmed order with no shipment or invoice evidence", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(confirmedSalesOrder)
      .mockReturnValueOnce([])
      .mockReturnValueOnce([]);
    spies.update.mockReturnValueOnce({ ...confirmedSalesOrder, status: "CANCELLED" });

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

    expectOk(result);
  });

  it("throws when posted shipment evidence exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(confirmedSalesOrder)
      .mockReturnValueOnce([postedShipment])
      .mockReturnValueOnce([]);

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

    expectErr(result, CancellationBlockedError);
  });

  it("throws when issued invoice evidence exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(confirmedSalesOrder)
      .mockReturnValueOnce([])
      .mockReturnValueOnce([{ ...baseSalesInvoice, status: "ISSUED" }]);

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

    expectErr(result, CancellationBlockedError);
  });
});
