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,
  basePurchaseOrderLine,
  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 };
    // 1. selectOne GoodsReceipt
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. selectFrom PurchaseOrderLine (by ids) → execute (array)
    spies.select.mockReturnValueOnce([basePurchaseOrderLine]);
    // 3. selectFrom GoodsReceiptLine (existing receipts) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 4. selectFrom GoodsReceipt (POSTED) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 5. updateTable GoodsReceipt
    spies.update.mockReturnValueOnce(updated);
    // 4. deleteFrom GoodsReceiptLine
    spies.delete.mockReturnValueOnce(undefined);
    // 5. 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 GoodsReceiptLine (existing receipts) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 4. 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 GoodsReceiptLine (existing receipts) → execute (array)
    spies.select.mockReturnValueOnce([]);
    // 4. selectFrom GoodsReceipt (POSTED) → execute (array)
    spies.select.mockReturnValueOnce([]);

    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>();
    // 1. GoodsReceipt (forUpdate)
    spies.select.mockReturnValueOnce(baseGoodsReceipt);
    // 2. PurchaseOrderLine
    spies.select.mockReturnValueOnce([basePurchaseOrderLine]);
    // 3. 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);
  });
});
