import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { baseActiveItem } from "../../item-management/testing/fixtures";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]); // Adjustment not found

    const result = await mock.withTx((trx) =>
      run(trx, { id: "nonexistent" }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectErr(result, StockAdjustmentNotFoundError);
  });

  it("locks the StockAdjustment row before validating status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    await mock.withTx((trx) =>
      run(trx, { id: "nonexistent" }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expect(mock.selects.filter((s) => /for update/i.test(s.sql))).toHaveLength(1);
  });

  it("returns error when stock adjustment is not in SUBMITTED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment]); // DRAFT status

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

  it("returns error when stock adjustment is not in SUBMITTED status (CONFIRMED)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseConfirmedAdjustment]); // CONFIRMED status

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

  // --- CORRECTION INCREASE ---

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

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line], // Lines
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel], // StockLevel lookup
      [ledgerEntry], // InventoryLedger insert
      [], // ItemValuation (no valuation)
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update (POSTED)
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel],
      [ledgerEntry], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [execution], // InventoryExecution update (POSTED)
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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(mock.updates.map((u) => u.updateValues())).toContainEqual(
      expect.objectContaining({ status: "POSTED", postedAt: expect.any(Date) as Date }),
    );
    expect(mock.inserts).toHaveLength(1);
  });

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    const value = expectOk(result as never);
    expect(value).toBeDefined();
    expect(mock.inserts).toHaveLength(2);
  });

  // --- CORRECTION DECREASE ---

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

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line], // Lines
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel], // StockLevel (onHand=100)
      [ledgerEntry], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "DECREASE",
      quantity: 200, // More than onHand (100)
    });

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectErr(result as never, InsufficientOnHandError);
    expect(mock.inserts).toHaveLength(0);
  });

  // --- SCRAP AVAILABLE ---

  it("confirms SCRAP (AVAILABLE) and creates 1 CR ledger entry (decreases onHand)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line], // Lines
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel], // StockLevel (onHand=100, blocked=5)
      [ledgerEntry], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("SCRAP");
    const lowStockLevel = { ...baseStockLevel, quantity: "2" };
    const line = makeLine({
      fromStockCategory: "AVAILABLE",
      quantity: 5,
    });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [lowStockLevel],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line], // Lines
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseBlockedStockLevel], // StockLevel (blocked=5 >= 3)
      [scrapEntry], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("SCRAP");
    const line = makeLine({
      fromStockCategory: "BLOCKED",
      quantity: 3,
    });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseBlockedStockLevel], // blocked=5
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    // Verify set was called (for StockLevel update and adjustment status)
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when blocked is insufficient for SCRAP (BLOCKED)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("SCRAP");
    const lowBlockedLevel = { ...baseBlockedStockLevel, quantity: "1" };
    const line = makeLine({
      fromStockCategory: "BLOCKED",
      quantity: 5, // More than blocked (1)
    });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [lowBlockedLevel],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("SCRAP");
    const line = makeLine({
      fromStockCategory: "AVAILABLE",
      quantity: 1,
      serialNumberId: "serial-1",
    });

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    // Verify serial number update happened
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [returnedSerial], // SerialNumber (RETURNED)
      [baseStockLevel],
      [
        {
          id: "ledger-1",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [], // SerialNumber update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [issuedSerial], // SerialNumber (ISSUED)
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectErr(result as never, InvalidSerialStateForScrapError);
    expect(mock.inserts).toHaveLength(0);
  });

  // --- BLOCK ---

  it("confirms BLOCK and creates two ledger entries (CR + DR)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line], // Lines
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel], // Available StockLevel
      [], // Blocked StockLevel
      [baseStorageLocation], // Location
      [{ id: "location-1" }], // Site locations
      [baseStockLevel], // Site stock levels
      [], // Active reservations
      [blockCR], // InventoryLedger insert (CR/AVAILABLE)
      [blockDR], // InventoryLedger insert (DR/BLOCKED)
      [], // Available StockLevel update (ignored)
      [], // Blocked StockLevel insert (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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");
    const insertedRows = mock.inserts.map((i) => i.insertValues());
    expect(insertedRows).toContainEqual(
      expect.objectContaining({ dcIndicator: "CR", stockType: "AVAILABLE" }),
    );
    expect(insertedRows).toContainEqual(
      expect.objectContaining({ dcIndicator: "DR", stockType: "BLOCKED" }),
    );
  });

  it("confirms BLOCK and increases blocked without changing onHand", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("BLOCK");
    const line = makeLine({ quantity: 10 });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel],
      [],
      [baseStorageLocation], // Location
      [{ id: "location-1" }], // Site locations
      [baseStockLevel], // Site stock levels
      [], // Active reservations
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert (AVAILABLE)
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (BLOCKED)
      [], // Available StockLevel update (ignored)
      [], // Blocked StockLevel insert (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    // set should be called for StockLevel blocked update and status update
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

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

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

  // --- UNBLOCK ---

  it("confirms UNBLOCK and creates two ledger entries (DR + CR)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line], // Lines
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [], // Available StockLevel
      [baseBlockedStockLevel], // StockLevel (blocked=5 >= 5)
      [unblockDR], // InventoryLedger insert (DR/AVAILABLE)
      [unblockCR], // InventoryLedger insert (CR/BLOCKED)
      [], // Available StockLevel insert (ignored)
      [], // Blocked StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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");
    const insertedRows = mock.inserts.map((i) => i.insertValues());
    expect(insertedRows).toContainEqual(
      expect.objectContaining({ dcIndicator: "DR", stockType: "AVAILABLE" }),
    );
    expect(insertedRows).toContainEqual(
      expect.objectContaining({ dcIndicator: "CR", stockType: "BLOCKED" }),
    );
  });

  it("confirms UNBLOCK and decreases blocked without changing onHand", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("UNBLOCK");
    const line = makeLine({ quantity: 5 });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [], // Available StockLevel
      [baseBlockedStockLevel], // blocked=5
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (AVAILABLE)
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert (BLOCKED)
      [], // Available StockLevel insert (ignored)
      [], // Blocked StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when blocked stock is insufficient for UNBLOCK", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("UNBLOCK");
    const lowBlockedLevel = { ...baseBlockedStockLevel, quantity: "2" };
    const line = makeLine({ quantity: 5 }); // More than blocked (2)

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [], // Available StockLevel
      [lowBlockedLevel],
    );

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

  // --- Valuation ---

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    // ItemValuation update happened inside applyValuation
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("triggers valuation CR for CORRECTION DECREASE and SCRAP (both categories)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "DECREASE",
      quantity: 5,
    });

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("does not trigger valuation for BLOCK and UNBLOCK", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("BLOCK");
    const line = makeLine({ quantity: 5 });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel],
      [],
      [baseStorageLocation], // Location
      [{ id: "location-1" }], // Site locations
      [baseStockLevel], // Site stock levels
      [], // Active reservations
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert (AVAILABLE)
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (BLOCKED)
      [], // Available StockLevel update (ignored)
      [], // Blocked StockLevel insert (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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(mock.selects).toHaveLength(10);
  });

  // --- LotStockLevel ---

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    // update should be called for StockLevel, LotStockLevel, and StockAdjustment status
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel],
      [],
      [baseStorageLocation], // Location
      [{ id: "location-1" }], // Site locations
      [baseStockLevel], // Site stock levels
      [], // Active reservations
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert (AVAILABLE)
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (BLOCKED)
      [], // Available StockLevel update (ignored)
      [], // Blocked StockLevel insert (ignored)
      [baseLotStockLevel], // LotStockLevel select
      [], // LotStockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [], // available StockLevel is created
      [baseBlockedStockLevel], // blocked=5
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (AVAILABLE)
      [
        {
          id: "ledger",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert (BLOCKED)
      [], // Available StockLevel insert (ignored)
      [], // Blocked StockLevel update (ignored)
      [lotWithBlocked], // LotStockLevel select
      [], // LotStockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );
    expectOk(result as never);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  // --- InventoryExecution linkage ---

  it("links ledger entries to the stock adjustment InventoryExecution", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
    });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel],
      [
        {
          id: "ledger-1",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ inventoryExecutionId: "execution-1" }),
    );
  });

  it("rejects aggregate CORRECTION DECREASE when duplicate stock keys exceed on-hand", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    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" };

    mock.enqueueResults(
      [adjustment],
      [makeExecution()],
      [line1, line2],
      makeExecutionLines(adjustment, [line1, line2]),
      [stockLevel],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expectErr(result as never, InsufficientOnHandError);
    expect(mock.inserts).toHaveLength(0);
  });

  it("applies aggregate CORRECTION INCREASE once per stock key", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    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" };

    mock.enqueueResults(
      [adjustment],
      [makeExecution()],
      [line1, line2],
      makeExecutionLines(adjustment, [line1, line2]),
      [stockLevel], // StockLevel (aggregated key)
      [
        {
          id: "ledger-1",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (line1)
      [], // ItemValuation (line1)
      [
        {
          id: "ledger-2",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert (line2)
      [], // ItemValuation (line2)
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expectOk(result as never);
    expect(mock.updates.map((u) => u.updateValues())).toContainEqual(
      expect.objectContaining({ quantity: "110" }),
    );
  });

  it("updates lot stock from the InventoryExecutionLine snapshot", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("CORRECTION");
    const currentLine = makeLine({
      lotId: "lot-current",
      quantity: "5",
    });
    const executionLine = makeExecutionLine(currentLine, {
      lotId: "lot-snapshot",
      quantity: "5",
    });

    mock.enqueueResults(
      [adjustment],
      [makeExecution()],
      [currentLine],
      [executionLine],
      [baseStockLevel],
      [
        {
          id: "ledger-1",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [{ ...baseLotStockLevel, lotId: "lot-snapshot" }], // LotStockLevel select
      [], // LotStockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expectOk(result as never);
    const lotSelect = mock.selects.find(
      (s) => s.sql.includes('"LotStockLevel"') && /"lotId"/.test(s.sql),
    );
    expect(lotSelect?.parameters).toContain("lot-snapshot");
    expect(mock.executedQueries.every((q) => !q.parameters.includes("lot-current"))).toBe(true);
  });

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

    mock.enqueueResults(
      [adjustment],
      [makeExecution()],
      [currentLine],
      [executionLine],
      [{ ...baseAvailableSerial, id: "serial-snapshot" }], // SerialNumber select
      [baseStockLevel],
      [
        {
          id: "ledger-1",
          inventoryExecutionId: "execution-1",
          dcIndicator: "CR",
        },
      ], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [], // SerialNumber update (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: adjustment.id }, ctx, mockItemManagementQueries(baseActiveItem)),
    );

    expectOk(result as never);
    const serialSelect = mock.selects.find((s) => s.sql.includes('"SerialNumber"'));
    expect(serialSelect?.parameters).toContain("serial-snapshot");
    expect(mock.executedQueries.every((q) => !q.parameters.includes("serial-current"))).toBe(true);
  });

  // --- Status transition ---

  it("transitions status from SUBMITTED to CONFIRMED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const adjustment = makeAdjustment("CORRECTION");
    const line = makeLine({
      adjustmentDirection: "INCREASE",
      quantity: 5,
    });
    const confirmedAdjustment = { ...adjustment, status: "CONFIRMED" };

    mock.enqueueResults(
      [adjustment],
      [makeExecution()], // InventoryExecution
      [line],
      makeExecutionLines(adjustment, [line]), // InventoryExecutionLines
      [baseStockLevel],
      [
        {
          id: "ledger-1",
          inventoryExecutionId: "execution-1",
          dcIndicator: "DR",
        },
      ], // InventoryLedger insert
      [], // ItemValuation
      [], // StockLevel update (ignored)
      [makeExecution()], // InventoryExecution update
      [confirmedAdjustment], // StockAdjustment update
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };

    mock.enqueueResults(
      [adjustment], // StockAdjustment
      [makeExecution()], // InventoryExecution
      [line1, line2], // Lines
      makeExecutionLines(adjustment, [line1, line2]), // InventoryExecutionLines
      [baseStockLevel], // StockLevel for line1
      [], // StockLevel for line2 (not found)
      [ledger1], // Ledger for line1
      [], // ItemValuation for line1
      [ledger2], // Ledger for line2
      [], // ItemValuation for line2
      [], // StockLevel update for line1 (ignored)
      [{ id: "new-stock-level" }], // StockLevel insert for line2 (ignored)
      [makeExecution()], // InventoryExecution update
      [{ ...adjustment, status: "CONFIRMED" }], // StockAdjustment update
    );

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

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