import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  StockAdjustmentNotFoundError,
  StockAdjustmentLineNotFoundError,
  InvalidStatusError,
  EmptyAdjustmentLinesError,
  InvalidQuantityError,
  ItemNotFoundError,
  ItemNotActiveError,
  StorageLocationNotFoundError,
  StorageLocationNotActiveError,
  InvalidFromStockCategoryError,
  LotNotFoundError,
  SerialNotFoundError,
} from "../lib/errors.generated";
import { expectErr, expectOk, mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseDraftAdjustment,
  baseSubmittedAdjustment,
  baseRejectedAdjustment,
  baseConfirmedAdjustment,
  correctionIncreaseLine,
  baseStorageLocation,
  baseInactiveLocation,
  baseInactiveItem,
} from "../testing/fixtures";
import { run } from "./updateStockAdjustment";

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

  const mockGetItemFound = mockItemManagementQueries(baseActiveItem);
  const mockGetItemNotFound = mockItemManagementQueries(null);
  const mockGetItemInactive = mockItemManagementQueries(baseInactiveItem);

  const validLine = {
    itemId: "item-1",
    storageLocationId: "location-1",
    quantity: "10",
    adjustmentDirection: "INCREASE" as const,
  };

  it("returns error when stock adjustment does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-2" }, ctx, mockGetItemFound),
    );
    expectErr(result as never, InvalidStatusError);
  });

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

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-4" }, ctx, mockGetItemFound),
    );
    expectErr(result as never, InvalidStatusError);
  });

  it("updates reason code on a DRAFT adjustment", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedAdjustment = { ...baseDraftAdjustment, reasonCode: "updated-reason" };
    mock.enqueueResults(
      [baseDraftAdjustment], // StockAdjustment
      [correctionIncreaseLine], // StockAdjustmentLine (current lines)
      [updatedAdjustment], // updateTable StockAdjustment
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-1", headerPatch: { reasonCode: "updated-reason" } },
        ctx,
        mockGetItemFound,
      ),
    );
    const value = expectOk<{ stockAdjustment: { reasonCode: string } }>(result as never);

    expect(value.stockAdjustment.reasonCode).toBe("updated-reason");
  });

  it("updates a line in place so its id and createdAt survive the edit", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseDraftAdjustment], // StockAdjustment
      [correctionIncreaseLine], // StockAdjustmentLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: "adjustment-1",
          updateLines: [{ lineId: correctionIncreaseLine.id, linePatch: { quantity: "9" } }],
        },
        ctx,
        mockGetItemFound,
      ),
    );

    expectOk(result as never);
    expect(mock.deletes).toHaveLength(0);
    expect(mock.inserts).toHaveLength(0);
    expect(mock.updates[0].updateValues()).toEqual(expect.objectContaining({ quantity: "9" }));
  });

  it("adds a stock adjustment line via addLines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseDraftAdjustment], // StockAdjustment
      [correctionIncreaseLine], // StockAdjustmentLine (current lines)
      [baseStorageLocation], // StorageLocation bulk fetch
    );

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1", addLines: [validLine] }, ctx, mockGetItemFound),
    );

    expectOk(result as never);
    expect(mock.inserts[0].insertRows()).toHaveLength(1);
  });

  it("removes a stock adjustment line via removeLineIds", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const secondLine = { ...correctionIncreaseLine, id: "adj-line-extra" };
    mock.enqueueResults(
      [baseDraftAdjustment], // StockAdjustment
      [correctionIncreaseLine, secondLine], // StockAdjustmentLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-1", removeLineIds: [correctionIncreaseLine.id] },
        ctx,
        mockGetItemFound,
      ),
    );

    expectOk(result as never);
    expect(mock.deletes).toHaveLength(1);
  });

  it("transitions REJECTED adjustment back to DRAFT", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedAdjustment = {
      ...baseRejectedAdjustment,
      status: "DRAFT",
      rejectionReason: null,
    };
    mock.enqueueResults(
      [baseRejectedAdjustment], // StockAdjustment
      [correctionIncreaseLine], // StockAdjustmentLine (current lines)
      [updatedAdjustment], // updateTable StockAdjustment
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-3", headerPatch: { reasonCode: "revised-reason" } },
        ctx,
        mockGetItemFound,
      ),
    );
    const value = expectOk<{ stockAdjustment: { status: string; rejectionReason: string | null } }>(
      result as never,
    );
    expect(value.stockAdjustment.status).toBe("DRAFT");
    expect(value.stockAdjustment.rejectionReason).toBeNull();
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ status: "DRAFT", rejectionReason: null }),
    );
  });

  it("returns error when an update targets a missing line", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseDraftAdjustment], // StockAdjustment
      [correctionIncreaseLine], // StockAdjustmentLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: "adjustment-1",
          updateLines: [{ lineId: "missing-line", linePatch: { quantity: "9" } }],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expectErr(result as never, StockAdjustmentLineNotFoundError);
  });

  it("returns error when a removal would leave the adjustment without lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseDraftAdjustment], // StockAdjustment
      [correctionIncreaseLine], // StockAdjustmentLine (current lines)
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-1", removeLineIds: [correctionIncreaseLine.id] },
        ctx,
        mockGetItemFound,
      ),
    );
    expectErr(result as never, EmptyAdjustmentLinesError);
  });

  it("returns error when item does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1", addLines: [validLine] }, ctx, mockGetItemNotFound),
    );
    expectErr(result as never, ItemNotFoundError);
  });

  it("returns error when line quantity is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine], [baseStorageLocation]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-1", addLines: [{ ...validLine, quantity: "0" }] },
        ctx,
        mockGetItemFound,
      ),
    );
    expectErr(result as never, InvalidQuantityError);
  });

  it("returns error when storage location does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine], []);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1", addLines: [validLine] }, ctx, mockGetItemFound),
    );
    expectErr(result as never, StorageLocationNotFoundError);
  });

  it("returns error when item is not active", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1", addLines: [validLine] }, ctx, mockGetItemInactive),
    );
    expectErr(result as never, ItemNotActiveError);
  });

  it("returns error when storage location is not active", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const inactiveAtLocation1 = { ...baseInactiveLocation, id: "location-1" };
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine], [inactiveAtLocation1]);

    const result = await mock.withTx((trx) =>
      run(trx, { id: "adjustment-1", addLines: [validLine] }, ctx, mockGetItemFound),
    );
    expectErr(result as never, StorageLocationNotActiveError);
  });

  it("rejects fromStockCategory set on non-SCRAP lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine], [baseStorageLocation]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: "adjustment-1",
          addLines: [{ ...validLine, fromStockCategory: "AVAILABLE" as const }],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expectErr(result as never, InvalidFromStockCategoryError);
  });

  it("returns error when lot does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine], [baseStorageLocation], []);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-1", addLines: [{ ...validLine, lotId: "nonexistent-lot" }] },
        ctx,
        mockGetItemFound,
      ),
    );
    expectErr(result as never, LotNotFoundError);
  });

  it("returns error when serial number does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [correctionIncreaseLine], [baseStorageLocation], []);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "adjustment-1", addLines: [{ ...validLine, serialNumberId: "nonexistent-serial" }] },
        ctx,
        mockGetItemFound,
      ),
    );
    expectErr(result as never, SerialNotFoundError);
  });
});
