import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  GoodsReceiptNotDraftError,
  GoodsReceiptNotFoundError,
  InvalidReceivedQuantityError,
  NoOpenReceiptQuantityError,
  PurchaseOrderLineNotFoundError,
} from "../lib/errors.generated";
import {
  baseGoodsReceipt,
  baseGoodsReceiptLines,
  basePurchaseOrderLines,
  orderedPurchaseOrder,
  postedGoodsReceipt,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./updateGoodsReceipt";

describe("updateGoodsReceipt", () => {
  it("updates quantities on a draft goods receipt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...baseGoodsReceipt,
      lines: JSON.stringify([{ ...baseGoodsReceiptLines[0], quantity: 2 }]),
    };
    spies.select.mockReturnValueOnce(baseGoodsReceipt).mockReturnValueOnce(orderedPurchaseOrder);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      { id: baseGoodsReceipt.id, lines: [{ ...baseGoodsReceiptLines[0], quantity: 2 }] },
      commandCtx,
    );

    expect(expectOk(result).goodsReceipt.lines).toContain('"quantity":2');
  });

  it("updates receipt date on a draft goods receipt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseGoodsReceipt, receiptDate: new Date("2024-02-01T00:00:00.000Z") };
    spies.select.mockReturnValueOnce(baseGoodsReceipt).mockReturnValueOnce(orderedPurchaseOrder);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      { id: baseGoodsReceipt.id, receiptDate: updated.receiptDate },
      commandCtx,
    );

    expect(expectOk(result).goodsReceipt.receiptDate).toEqual(updated.receiptDate);
  });

  it("returns error when goods receipt does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    expectErr(await run(db, { id: "missing-receipt" }, commandCtx), GoodsReceiptNotFoundError);
  });

  it("returns error when goods receipt is not draft", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(postedGoodsReceipt);
    expectErr(await run(db, { id: postedGoodsReceipt.id }, commandCtx), GoodsReceiptNotDraftError);
  });

  it("returns error when updated line data is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt).mockReturnValueOnce(orderedPurchaseOrder);
    expectErr(
      await run(
        db,
        {
          id: baseGoodsReceipt.id,
          lines: [{ ...baseGoodsReceiptLines[0], purchaseOrderLineId: "missing-line" }],
        },
        commandCtx,
      ),
      PurchaseOrderLineNotFoundError,
    );
  });

  it("returns error when an updated receipt quantity is not positive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt).mockReturnValueOnce(orderedPurchaseOrder);

    expectErr(
      await run(
        db,
        { id: baseGoodsReceipt.id, lines: [{ ...baseGoodsReceiptLines[0], quantity: 0 }] },
        commandCtx,
      ),
      InvalidReceivedQuantityError,
    );
  });

  it("returns error when an updated receipt line has no open quantity remaining", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt).mockReturnValueOnce({
      ...orderedPurchaseOrder,
      lines: JSON.stringify([
        { ...basePurchaseOrderLines[0], receivedQuantity: basePurchaseOrderLines[0].quantity },
      ]),
    });

    expectErr(
      await run(
        db,
        { id: baseGoodsReceipt.id, lines: [{ ...baseGoodsReceiptLines[0], quantity: 1 }] },
        commandCtx,
      ),
      NoOpenReceiptQuantityError,
    );
  });
});
