import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { baseActiveItem } from "../../item-management/testing/fixtures";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  StockAdjustmentNotFoundError,
  InvalidStatusError,
  InsufficientOnHandError,
  InsufficientAvailableStockError,
  InsufficientBlockedStockError,
  InvalidSerialStateForScrapError,
} from "../lib/errors.generated";
import { expectOk, expectErr, mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseSubmittedAdjustment,
  baseDraftAdjustment,
  baseConfirmedAdjustment,
  correctionIncreaseLine,
  scrapAvailableLine,
  scrapBlockedLine,
  blockLine,
  unblockLine,
  baseStockLevel,
  baseBlockedStockLevel,
  baseStockReservation,
  baseStorageLocation,
  baseLotStockLevel,
  baseAvailableSerial,
  baseIssuedSerial,
  baseItemValuation,
} from "../testing/fixtures";
import { run } from "./confirmStockAdjustment";

describe("confirmStockAdjustment", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory:inventoryApproval:confirmStockAdjustment"],
  };

  // Helper to build a submitted adjustment with a specific type
  const makeAdjustment = (type: string) => ({
    ...baseSubmittedAdjustment,
    adjustmentType: type,
  });

  // Helper to build lines referencing adjustment-2 (submitted)
  const makeLine = (overrides: Record<string, unknown> = {}) => ({
    ...correctionIncreaseLine,
    stockAdjustmentId: baseSubmittedAdjustment.id,
    ...overrides,
  });

  const makeExecution = (overrides: Record<string, unknown> = {}) => ({
    id: "execution-1",
    executionType: "STOCK_ADJUSTMENT",
    status: "DRAFT",
    effectiveDate: baseSubmittedAdjustment.adjustmentDate,
    postedAt: null,
    sourceDocumentType: "STOCK_ADJUSTMENT",
    sourceDocumentId: baseSubmittedAdjustment.id,
    createdAt: new Date("2024-01-01T00:00:00.000Z"),
    updatedAt: null,
    ...overrides,
  });

  const makeExecutionLine = (
    line: ReturnType<typeof makeLine>,
    overrides: Record<string, unknown> = {},
  ) => ({
    id: `execution-line-${line.id}`,
    inventoryExecutionId: "execution-1",
    direction: line.adjustmentDirection === "INCREASE" ? "IN" : "OUT",
    itemId: line.itemId,
    quantity: line.quantity,
    unitId: baseActiveItem.unitId,
    primaryQuantity: line.quantity,
    primaryUnitId: baseActiveItem.unitId,
    unitConversionRate: "1",
    storageLocationId: line.storageLocationId,
    stockType: line.fromStockCategory === "BLOCKED" ? "BLOCKED" : "AVAILABLE",
    sourceLineId: line.id,
    lotId: line.lotId ?? null,
    serialNumberId: line.serialNumberId ?? null,
    createdAt: new Date("2024-01-01T00:00:00.000Z"),
    updatedAt: null,
    ...overrides,
  });

  const makeExecutionLines = (
    adjustment: { adjustmentType: string },
    lines: ReturnType<typeof makeLine>[],
  ) =>
    lines.flatMap((line) => {
      if (adjustment.adjustmentType === "BLOCK") {
        return [
          makeExecutionLine(line, { direction: "OUT", stockType: "AVAILABLE" }),
          makeExecutionLine(line, {
            id: `execution-line-${line.id}-blocked`,
            direction: "IN",
            stockType: "BLOCKED",
          }),
        ];
      }
      if (adjustment.adjustmentType === "UNBLOCK") {
        return [
          makeExecutionLine(line, { direction: "IN", stockType: "AVAILABLE" }),
          makeExecutionLine(line, {
            id: `execution-line-${line.id}-blocked`,
            direction: "OUT",
            stockType: "BLOCKED",
          }),
        ];
      }
      if (adjustment.adjustmentType === "SCRAP") {
        return [makeExecutionLine(line, { direction: "OUT" })];
      }
      return [makeExecutionLine(line)];
    });

  // --- Error scenarios ---

  it("returns error when stock adjustment does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // Adjustment not found

    const result = await run(
      db,
      { id: "nonexistent" },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result, StockAdjustmentNotFoundError);
  });

  it("locks the StockAdjustment row before validating status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    await run(db, { id: "nonexistent" }, ctx, mockItemManagementQueries(baseActiveItem));

    expect(spies.forUpdate).toHaveBeenCalledTimes(1);
  });

  it("returns error when stock adjustment is not in SUBMITTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment); // DRAFT status

    const result = await run(
      db,
      { id: baseDraftAdjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result, InvalidStatusError);
  });

  it("returns error when stock adjustment is not in SUBMITTED status (CONFIRMED)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseConfirmedAdjustment); // CONFIRMED status

    const result = await run(
      db,
      { id: baseConfirmedAdjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result, InvalidStatusError);
  });

  // --- CORRECTION INCREASE ---

  it("confirms CORRECTION INCREASE and creates DR ledger entry (increases onHand)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
      unitCost: 10,
    });
    const ledgerEntry = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel lookup
      .mockReturnValueOnce(undefined); // ItemValuation (no valuation)
    spies.insert.mockReturnValue(ledgerEntry);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      stockAdjustment: { status: string };
      inventoryLedgerEntries: { inventoryExecutionId: string; dcIndicator: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(1);
    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[0].dcIndicator).toBe("DR");
    expect(value.stockAdjustment.status).toBe("CONFIRMED");
  });

  it("creates InventoryExecution linkage when confirming through module wiring", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
      unitCost: 10,
    });
    const execution = makeExecution({ status: "POSTED" });
    const ledgerEntry = {
      id: "ledger-1",
      inventoryExecutionId: execution.id,
      dcIndicator: "DR",
    };

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce(ledgerEntry);
    spies.update
      .mockReturnValueOnce(execution)
      .mockReturnValueOnce({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryExecution: { id: string };
      inventoryLedgerEntries: { inventoryExecutionId: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe(execution.id);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "POSTED", postedAt: expect.any(Date) as Date }),
    );
    expect(spies.insert).toHaveBeenCalledTimes(1);
  });

  it("creates new StockLevel when none exists for CORRECTION INCREASE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
    });
    const ledgerEntry = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(undefined) // StockLevel not found
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert
      .mockReturnValueOnce(ledgerEntry) // Ledger entry
      .mockReturnValueOnce({ id: "new-stock-level" }); // StockLevel insert
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk(result as never);
    expect(value).toBeDefined();
    expect(spies.insert).toHaveBeenCalledTimes(2);
  });

  // --- CORRECTION DECREASE ---

  it("confirms CORRECTION DECREASE and creates CR ledger entry (decreases onHand)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "DECREASE",
      quantity: 5,
      unitCost: 10,
    });
    const ledgerEntry = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel (onHand=100)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue(ledgerEntry);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryLedgerEntries: { inventoryExecutionId: string; dcIndicator: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(1);
    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[0].dcIndicator).toBe("CR");
  });

  it("returns error when on-hand is insufficient for CORRECTION DECREASE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "DECREASE",
      quantity: 200, // More than onHand (100)
    });

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel); // StockLevel (onHand=100)

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result as never, InsufficientOnHandError);
    expect(spies.insert).not.toHaveBeenCalled();
  });

  // --- SCRAP AVAILABLE ---

  it("confirms SCRAP (AVAILABLE) and creates 1 CR ledger entry (decreases onHand)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const line = makeLine({
      ...scrapAvailableLine,
      stockAdjustmentId: adjustment.id,
      quantity: 3,
      fromStockCategory: "AVAILABLE",
    });
    const ledgerEntry = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel (onHand=100, blocked=5)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue(ledgerEntry);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryLedgerEntries: { inventoryExecutionId: string; dcIndicator: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(1);
    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[0].dcIndicator).toBe("CR");
  });

  it("returns error when available portion is insufficient for SCRAP (AVAILABLE)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const lowStockLevel = { ...baseStockLevel, quantity: "2" };
    const line = makeLine({
      fromStockCategory: "AVAILABLE",
      quantity: 5,
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(lowStockLevel);

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result as never, InsufficientOnHandError);
  });

  // --- SCRAP BLOCKED ---

  it("confirms SCRAP (BLOCKED) and creates a single SCRAP/CR ledger entry", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const line = makeLine({
      ...scrapBlockedLine,
      stockAdjustmentId: adjustment.id,
      quantity: 3,
      fromStockCategory: "BLOCKED",
    });
    const scrapEntry = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseBlockedStockLevel) // StockLevel (blocked=5 >= 3)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValueOnce(scrapEntry);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryLedgerEntries: { inventoryExecutionId: string; dcIndicator: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(1);
    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[0].dcIndicator).toBe("CR");
  });

  it("confirms SCRAP (BLOCKED) and decreases the BLOCKED StockLevel type", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const line = makeLine({
      fromStockCategory: "BLOCKED",
      quantity: 3,
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseBlockedStockLevel) // blocked=5
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    // Verify set was called (for StockLevel update and adjustment status)
    expect(spies.set).toHaveBeenCalled();
  });

  it("returns error when blocked is insufficient for SCRAP (BLOCKED)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const lowBlockedLevel = { ...baseBlockedStockLevel, quantity: "1" };
    const line = makeLine({
      fromStockCategory: "BLOCKED",
      quantity: 5, // More than blocked (1)
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(lowBlockedLevel);

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result as never, InsufficientBlockedStockError);
  });

  // --- SCRAP serial number transitions ---

  it("confirms SCRAP and transitions serial number from AVAILABLE to SCRAPPED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const line = makeLine({
      fromStockCategory: "AVAILABLE",
      quantity: 1,
      serialNumberId: "serial-1",
    });

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseAvailableSerial) // SerialNumber (AVAILABLE)
      .mockReturnValueOnce(baseStockLevel) // StockLevel (onHand-blocked >= 1)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    // Verify serial number update happened
    expect(spies.update).toHaveBeenCalled();
  });

  it("confirms SCRAP and transitions serial number from RETURNED to SCRAPPED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const returnedSerial = { ...baseAvailableSerial, id: "serial-ret", status: "RETURNED" };
    const line = makeLine({
      fromStockCategory: "AVAILABLE",
      quantity: 1,
      serialNumberId: "serial-ret",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(returnedSerial) // SerialNumber (RETURNED)
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    expect(spies.update).toHaveBeenCalled();
  });

  it("rejects SCRAP when serial is in ISSUED or SCRAPPED state", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const issuedSerial = { ...baseIssuedSerial, status: "ISSUED" };
    const line = makeLine({
      fromStockCategory: "AVAILABLE",
      quantity: 1,
      serialNumberId: "serial-2",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(issuedSerial); // SerialNumber (ISSUED)

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result as never, InvalidSerialStateForScrapError);
    expect(spies.insert).not.toHaveBeenCalled();
  });

  // --- BLOCK ---

  it("confirms BLOCK and creates two ledger entries (CR + DR)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("BLOCK");
    const line = makeLine({
      ...blockLine,
      stockAdjustmentId: adjustment.id,
      quantity: 10,
    });
    const blockCR = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    };
    const blockDR = {
      id: "ledger-2",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // Available StockLevel
      .mockReturnValueOnce(undefined) // Blocked StockLevel
      .mockReturnValueOnce(baseStorageLocation) // Location
      .mockReturnValueOnce([{ id: "location-1" }]) // Site locations
      .mockReturnValueOnce([baseStockLevel]) // Site stock levels
      .mockReturnValueOnce([]); // Active reservations
    spies.insert.mockReturnValueOnce(blockCR).mockReturnValueOnce(blockDR);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryLedgerEntries: { inventoryExecutionId: string; dcIndicator: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(2);
    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[0].dcIndicator).toBe("CR");
    expect(value.inventoryLedgerEntries[1].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[1].dcIndicator).toBe("DR");
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ dcIndicator: "CR", stockType: "AVAILABLE" }),
    );
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ dcIndicator: "DR", stockType: "BLOCKED" }),
    );
  });

  it("confirms BLOCK and increases blocked without changing onHand", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("BLOCK");
    const line = makeLine({ quantity: 10 });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(baseStorageLocation) // Location
      .mockReturnValueOnce([{ id: "location-1" }]) // Site locations
      .mockReturnValueOnce([baseStockLevel]) // Site stock levels
      .mockReturnValueOnce([]); // Active reservations
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    // set should be called for StockLevel blocked update and status update
    expect(spies.set).toHaveBeenCalled();
  });

  it("returns error when available stock is insufficient for BLOCK", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("BLOCK");
    // available = 100 - 10 - 5 = 85, requesting 100
    const line = makeLine({ quantity: 100 });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(baseStorageLocation)
      .mockReturnValueOnce([{ id: "location-1" }])
      .mockReturnValueOnce([baseStockLevel])
      .mockReturnValueOnce([baseStockReservation]);

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result as never, InsufficientAvailableStockError);
  });

  // --- UNBLOCK ---

  it("confirms UNBLOCK and creates two ledger entries (DR + CR)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("UNBLOCK");
    const line = makeLine({
      ...unblockLine,
      stockAdjustmentId: adjustment.id,
      quantity: 5,
    });
    const unblockDR = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };
    const unblockCR = {
      id: "ledger-2",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(undefined) // Available StockLevel
      .mockReturnValueOnce(baseBlockedStockLevel); // StockLevel (blocked=5 >= 5)
    spies.insert.mockReturnValueOnce(unblockDR).mockReturnValueOnce(unblockCR);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryLedgerEntries: { inventoryExecutionId: string; dcIndicator: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(2);
    expect(value.inventoryLedgerEntries[0].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[0].dcIndicator).toBe("DR");
    expect(value.inventoryLedgerEntries[1].inventoryExecutionId).toBe("execution-1");
    expect(value.inventoryLedgerEntries[1].dcIndicator).toBe("CR");
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ dcIndicator: "DR", stockType: "AVAILABLE" }),
    );
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ dcIndicator: "CR", stockType: "BLOCKED" }),
    );
  });

  it("confirms UNBLOCK and decreases blocked without changing onHand", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("UNBLOCK");
    const line = makeLine({ quantity: 5 });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(baseBlockedStockLevel); // blocked=5
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    expect(spies.set).toHaveBeenCalled();
  });

  it("returns error when blocked stock is insufficient for UNBLOCK", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("UNBLOCK");
    const lowBlockedLevel = { ...baseBlockedStockLevel, quantity: "2" };
    const line = makeLine({ quantity: 5 }); // More than blocked (2)

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(lowBlockedLevel);

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectErr(result as never, InsufficientBlockedStockError);
  });

  // --- Valuation ---

  it("triggers valuation DR for CORRECTION INCREASE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 10,
      unitCost: 5,
    });
    const ledgerEntry = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel
      .mockReturnValueOnce(baseItemValuation) // ItemValuation (for applyValuation)
      .mockReturnValueOnce({ id: "policy-1", costingMethod: "AVCO", standardCostRate: null }); // ValuationPolicy
    spies.insert.mockReturnValue(ledgerEntry);
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    // ItemValuation update happened inside applyValuation
    expect(spies.update).toHaveBeenCalled();
  });

  it("triggers valuation CR for CORRECTION DECREASE and SCRAP (both categories)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "DECREASE",
      quantity: 5,
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel
      .mockReturnValueOnce(baseItemValuation) // ItemValuation
      .mockReturnValueOnce({ id: "policy-1", costingMethod: "AVCO", standardCostRate: null }); // ValuationPolicy
    spies.insert.mockReturnValue({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    expect(spies.update).toHaveBeenCalled();
  });

  it("does not trigger valuation for BLOCK and UNBLOCK", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("BLOCK");
    const line = makeLine({ quantity: 5 });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(baseStorageLocation) // Location
      .mockReturnValueOnce([{ id: "location-1" }]) // Site locations
      .mockReturnValueOnce([baseStockLevel]) // Site stock levels
      .mockReturnValueOnce([]); // Active reservations
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    // For BLOCK, applyValuation is NOT called, so no extra selects for ItemValuation.
    // Selects include stock, site availability, reservation, and blocked-stock lookups.
    expect(spies.select).toHaveBeenCalledTimes(10);
  });

  // --- LotStockLevel ---

  it("updates LotStockLevel onHand when lotId provided on CORRECTION/SCRAP", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 10,
      lotId: "lot-1",
    });

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel
      .mockReturnValueOnce(baseLotStockLevel) // LotStockLevel
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    // update should be called for StockLevel, LotStockLevel, and StockAdjustment status
    expect(spies.update).toHaveBeenCalled();
  });

  it("updates LotStockLevel blocked when lotId provided on BLOCK/UNBLOCK/SCRAP(BLOCKED)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("BLOCK");
    const line = makeLine({
      quantity: 5,
      lotId: "lot-1",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(baseStorageLocation) // Location
      .mockReturnValueOnce([{ id: "location-1" }]) // Site locations
      .mockReturnValueOnce([baseStockLevel]) // Site stock levels
      .mockReturnValueOnce([]) // Active reservations
      .mockReturnValueOnce(baseLotStockLevel); // LotStockLevel
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    expect(spies.update).toHaveBeenCalled();
  });

  it("updates LotStockLevel blocked when lotId provided on UNBLOCK", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("UNBLOCK");
    const lotWithBlocked = { ...baseLotStockLevel, blocked: 10 };
    const line = makeLine({
      quantity: 5,
      lotId: "lot-1",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(undefined) // available StockLevel is created
      .mockReturnValueOnce(baseBlockedStockLevel) // blocked=5
      .mockReturnValueOnce(lotWithBlocked); // LotStockLevel
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    expect(spies.update).toHaveBeenCalled();
  });

  it("updates LotStockLevel onHand and blocked when lotId provided on SCRAP (BLOCKED)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const lotWithBlocked = { ...baseLotStockLevel, onHand: 50, blocked: 10 };
    const line = makeLine({
      fromStockCategory: "BLOCKED",
      quantity: 3,
      lotId: "lot-1",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseBlockedStockLevel) // blocked=5 >= 3
      .mockReturnValueOnce(lotWithBlocked) // LotStockLevel
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    expectOk(result as never);
    expect(spies.update).toHaveBeenCalled();
  });

  // --- InventoryExecution linkage ---

  it("links ledger entries to the stock adjustment InventoryExecution", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    await run(db, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem));

    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({ inventoryExecutionId: "execution-1" }),
    );
  });

  it("rejects aggregate CORRECTION DECREASE when duplicate stock keys exceed on-hand", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line1 = makeLine({
      id: "adj-line-agg-1",
      adjustmentDirection: "DECREASE",
      quantity: "60",
    });
    const line2 = makeLine({
      id: "adj-line-agg-2",
      adjustmentDirection: "DECREASE",
      quantity: "60",
    });
    const stockLevel = { ...baseStockLevel, quantity: "100" };

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution())
      .mockReturnValueOnce([line1, line2])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line1, line2]))
      .mockReturnValueOnce(stockLevel);

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );

    expectErr(result as never, InsufficientOnHandError);
    expect(spies.insert).not.toHaveBeenCalled();
  });

  it("applies aggregate CORRECTION INCREASE once per stock key", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line1 = makeLine({
      id: "adj-line-agg-1",
      adjustmentDirection: "INCREASE",
      quantity: "5",
    });
    const line2 = makeLine({
      id: "adj-line-agg-2",
      adjustmentDirection: "INCREASE",
      quantity: "5",
    });
    const stockLevel = { ...baseStockLevel, quantity: "100" };

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution())
      .mockReturnValueOnce([line1, line2])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line1, line2]))
      .mockReturnValueOnce(stockLevel)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce(undefined);
    spies.insert
      .mockReturnValueOnce({
        id: "ledger-1",
        inventoryExecutionId: "execution-1",
        dcIndicator: "DR",
      })
      .mockReturnValueOnce({
        id: "ledger-2",
        inventoryExecutionId: "execution-1",
        dcIndicator: "DR",
      });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );

    expectOk(result as never);
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ quantity: "110" }));
  });

  it("updates lot stock from the InventoryExecutionLine snapshot", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const currentLine = makeLine({
      lotId: "lot-current",
      quantity: "5",
    });
    const executionLine = makeExecutionLine(currentLine, {
      lotId: "lot-snapshot",
      quantity: "5",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution())
      .mockReturnValueOnce([currentLine])
      .mockReturnValueOnce([executionLine])
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined)
      .mockReturnValueOnce({ ...baseLotStockLevel, lotId: "lot-snapshot" });
    spies.insert.mockReturnValueOnce({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );

    expectOk(result as never);
    expect(spies.where).toHaveBeenCalledWith("lotId", "=", "lot-snapshot");
    expect(spies.where).not.toHaveBeenCalledWith("lotId", "=", "lot-current");
  });

  it("validates scrap serial state from the InventoryExecutionLine snapshot", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("SCRAP");
    const currentLine = makeLine({
      ...scrapAvailableLine,
      stockAdjustmentId: adjustment.id,
      serialNumberId: "serial-current",
    });
    const executionLine = makeExecutionLine(currentLine, {
      direction: "OUT",
      serialNumberId: "serial-snapshot",
    });

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution())
      .mockReturnValueOnce([currentLine])
      .mockReturnValueOnce([executionLine])
      .mockReturnValueOnce({ ...baseAvailableSerial, id: "serial-snapshot" })
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined);
    spies.insert.mockReturnValueOnce({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "CR",
    });
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );

    expectOk(result as never);
    expect(spies.where).toHaveBeenCalledWith("id", "=", "serial-snapshot");
    expect(spies.where).not.toHaveBeenCalledWith("id", "=", "serial-current");
  });

  // --- Status transition ---

  it("transitions status from SUBMITTED to CONFIRMED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
    });
    const confirmedAdjustment = { ...adjustment, status: "CONFIRMED" };

    spies.select
      .mockReturnValueOnce(adjustment)
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line])
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel)
      .mockReturnValueOnce(undefined); // ItemValuation
    spies.insert.mockReturnValue({
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    });
    spies.update.mockReturnValue(confirmedAdjustment);

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      stockAdjustment: { status: string };
    }>(result as never);

    expect(value.stockAdjustment.status).toBe("CONFIRMED");
  });

  // --- Multiple lines ---

  it("processes multiple lines in a single confirmation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const adjustment = makeAdjustment("CORRECTION");
    const line1 = makeLine({ adjustmentDirection: "INCREASE", quantity: 5 });
    const line2 = makeLine({
      id: "adj-line-2b",
      adjustmentDirection: "INCREASE",
      quantity: 3,
      itemId: "item-2",
    });

    const ledger1 = {
      id: "ledger-1",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };
    const ledger2 = {
      id: "ledger-2",
      inventoryExecutionId: "execution-1",
      dcIndicator: "DR",
    };

    spies.select
      .mockReturnValueOnce(adjustment) // StockAdjustment
      .mockReturnValueOnce(makeExecution()) // InventoryExecution
      .mockReturnValueOnce([line1, line2]) // Lines
      .mockReturnValueOnce(makeExecutionLines(adjustment, [line1, line2])) // InventoryExecutionLines
      .mockReturnValueOnce(baseStockLevel) // StockLevel for line1
      .mockReturnValueOnce(undefined) // ItemValuation for line1
      .mockReturnValueOnce(undefined) // StockLevel for line2 (not found)
      .mockReturnValueOnce(undefined); // ItemValuation for line2
    spies.insert
      .mockReturnValueOnce(ledger1) // Ledger for line1
      .mockReturnValueOnce({ id: "execution-line-2" }) // InventoryExecutionLine for line2
      .mockReturnValueOnce(ledger2) // Ledger for line2
      .mockReturnValueOnce({ id: "new-stock-level" }); // StockLevel insert for line2
    spies.update.mockReturnValue({ ...adjustment, status: "CONFIRMED" });

    const result = await run(
      db,
      { id: adjustment.id },
      ctx,
      mockItemManagementQueries(baseActiveItem),
    );
    const value = expectOk<{
      inventoryLedgerEntries: { id: string }[];
    }>(result as never);

    expect(value.inventoryLedgerEntries).toHaveLength(2);
  });
});
