import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidShipmentLineError, ShipmentNotEditableError } from "../lib/errors.generated";
import {
  baseSalesOrderLine,
  baseShipment,
  baseShipmentLine,
  baseShipmentLineInput,
  postedShipment,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./updateShipment";

describe("updateShipment", () => {
  it("updates draft shipment metadata", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: baseShipment.salesOrderId };
    spies.select.mockReturnValueOnce(baseShipment).mockReturnValueOnce(orderLine);
    spies.update.mockReturnValueOnce({
      ...baseShipment,
      trackingNumber: "TRACK-001",
      updatedAt: new Date(),
    });
    spies.insert.mockReturnValueOnce(baseShipmentLine);

    const result = await run(
      db,
      {
        shipmentId: baseShipment.id,
        trackingNumber: "TRACK-001",
        lines: [baseShipmentLineInput],
      },
      commandCtx,
    );

    expectOk(result);
    expect(spies.delete).toHaveBeenCalled();
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ trackingNumber: "TRACK-001" }),
    );
  });

  it("returns error when updating a posted shipment", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(postedShipment);

    const result = await run(
      db,
      { shipmentId: postedShipment.id, trackingNumber: "TRACK-001" },
      commandCtx,
    );

    expectErr(result, ShipmentNotEditableError);
  });

  it("returns error when updated quantity exceeds remaining order quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderLine = {
      ...baseSalesOrderLine,
      salesOrderId: baseShipment.salesOrderId,
      shippedQuantity: 9,
      quantity: 10,
    };
    spies.select.mockReturnValueOnce(baseShipment).mockReturnValueOnce(orderLine);

    const result = await run(
      db,
      {
        shipmentId: baseShipment.id,
        lines: [{ ...baseShipmentLineInput, quantity: 2 }],
      },
      commandCtx,
    );

    expectErr(result, InvalidShipmentLineError);
  });
});
