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 { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseGoodsReceipt,
  baseGoodsReceiptLines,
  basePurchaseOrderLine,
  baseUnit,
  orderedPurchaseOrder,
  postedGoodsReceipt,
} from "../testing/fixtures";
import { run } from "./updateGoodsReceipt";

describe("updateGoodsReceipt", () => {
  it("updates quantities on a draft goods receipt", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseGoodsReceipt };
    // 1. selectOne GoodsReceipt
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. selectFrom PurchaseOrderLine (by ids) → execute (array)
    spies.select.mockReturnValueOnce([basePurchaseOrderLine]);
    // 3. selectFrom PurchaseOrder (PO headers) → execute (array)
    spies.select.mockReturnValueOnce([orderedPurchaseOrder]);
    // 4. selectFrom GoodsReceiptLine (existing receipts) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 5. selectFrom GoodsReceipt (POSTED) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 6. updateTable GoodsReceipt
    spies.update.mockReturnValueOnce(updated);
    // 7. deleteFrom GoodsReceiptLine
    spies.delete.mockReturnValueOnce(undefined);
    // 8. insertInto GoodsReceiptLine
    spies.insert.mockReturnValueOnce(undefined);

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

    expect(expectOk(result).goodsReceipt).toBeDefined();
  });

  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") };
    // 1. selectOne GoodsReceipt
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. updateTable GoodsReceipt
    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>();
    // 1. selectOne GoodsReceipt
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. selectFrom PurchaseOrderLine (by ids) → execute (empty array — line not found)
    spies.select.mockReturnValueOnce([]);
    // 3. selectFrom PurchaseOrder (PO headers) → execute (empty — no PO lines found)
    spies.select.mockReturnValueOnce([]);
    // 4. selectFrom GoodsReceiptLine (existing receipts) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 5. selectFrom GoodsReceipt (POSTED) → execute (array)
    spies.select.mockReturnValueOnce([]);
    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>();
    // 1. selectOne GoodsReceipt
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. selectFrom PurchaseOrderLine (by ids) → execute (array)
    spies.select.mockReturnValueOnce([basePurchaseOrderLine]);
    // 3. selectFrom PurchaseOrder (PO headers) → execute (array)
    spies.select.mockReturnValueOnce([orderedPurchaseOrder]);
    // 4. selectFrom GoodsReceiptLine (existing receipts) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 5. selectFrom GoodsReceipt (POSTED) → execute (array)
    spies.select.mockReturnValueOnce([]);

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

  it("updates a draft goods receipt without providing lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseGoodsReceipt, receiptDate: new Date("2024-03-01T00:00:00.000Z") };
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    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 a PO-unlinked line has non-positive quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseGoodsReceipt);

    const result = await run(
      db,
      {
        id: baseGoodsReceipt.id,
        lines: [
          { quantity: "0", purchaseOrderLineId: null, itemId: "item-1", unitId: baseUnit.id },
        ],
      },
      commandCtx,
    );

    expectErr(result, InvalidReceivedQuantityError);
  });

  it("accepts PO-unlinked lines with valid quantity", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseGoodsReceipt };
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    spies.update.mockReturnValueOnce(updated);
    spies.delete.mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        id: baseGoodsReceipt.id,
        lines: [
          {
            quantity: "5",
            purchaseOrderLineId: null,
            itemId: "item-1",
            unitId: baseUnit.id,
            requiresInventoryHandoff: false,
            destinationSite: null,
            destinationStorageLocation: null,
          },
        ],
      },
      commandCtx,
    );

    expect(expectOk(result).goodsReceipt).toBeDefined();
  });

  it("uses PO line defaults for itemId, unitId, and receiving site when not provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseGoodsReceipt };
    spies.select
      .mockReturnValueOnce(baseGoodsReceipt)
      .mockReturnValueOnce([basePurchaseOrderLine]) // PurchaseOrderLine
      .mockReturnValueOnce([orderedPurchaseOrder]) // PurchaseOrder (PO headers)
      .mockReturnValueOnce([]) // GoodsReceiptLine
      .mockReturnValueOnce([]); // GoodsReceipt POSTED
    spies.update.mockReturnValueOnce(updated);
    spies.delete.mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce(undefined);

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

    expectOk(result);
    const valuesCall = spies.values.mock.calls[0]?.[0] as Record<string, unknown>[];
    expect(valuesCall[0]).toEqual(
      expect.objectContaining({
        itemId: basePurchaseOrderLine.itemId,
        unitId: basePurchaseOrderLine.unitId,
        destinationSite: basePurchaseOrderLine.receivingSiteId,
        requiresInventoryHandoff: basePurchaseOrderLine.requiresPhysicalReceipt,
      }),
    );
  });

  it("returns error when an updated receipt line has no open quantity remaining", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. GoodsReceipt (forUpdate)
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. PurchaseOrderLine
    spies.select.mockReturnValueOnce([basePurchaseOrderLine]);
    // 3. PurchaseOrder (PO headers)
    spies.select.mockReturnValueOnce([orderedPurchaseOrder]);
    // 4. GoodsReceiptLine — fully received
    spies.select.mockReturnValueOnce([
      {
        goodsReceiptId: "posted-gr-1",
        purchaseOrderLineId: basePurchaseOrderLine.id,
        quantity: 10,
      },
    ]);
    // 4. GoodsReceipt (POSTED)
    spies.select.mockReturnValueOnce([{ id: "posted-gr-1", status: "POSTED" }]);

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

    expectErr(result, NoOpenReceiptQuantityError);
  });
});
