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 {
  ReasonCodeRequiredError,
  EmptyAdjustmentLinesError,
  InvalidQuantityError,
  ItemNotFoundError,
  ItemNotActiveError,
  StorageLocationNotFoundError,
  StorageLocationNotActiveError,
  InvalidFromStockCategoryError,
  LotNotFoundError,
  SerialNotFoundError,
} from "../lib/errors.generated";
import { expectOk, mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseDraftAdjustment,
  baseStorageLocation,
  baseInactiveLocation,
  baseActiveLot,
  baseAvailableSerial,
  baseInactiveItem,
} from "../testing/fixtures";
import { run } from "./createStockAdjustment";

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

  const mockGetItemFound = mockItemManagementQueries(baseActiveItem);

  const mockGetItemNotFound = mockItemManagementQueries(null);

  const mockGetItemInactive = mockItemManagementQueries(baseInactiveItem);

  const validLine = {
    itemId: "item-1",
    storageLocationId: "location-1",
    quantity: "5",
    adjustmentDirection: "INCREASE" as const,
  };
  const adjustmentDate = new Date("2024-01-01T00:00:00.000Z");

  it("returns error when reason code is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "", adjustmentDate },
          lines: [validLine],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ReasonCodeRequiredError);
    }
  });

  it("returns error when no lines are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        { header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate }, lines: [] },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(EmptyAdjustmentLinesError);
    }
  });

  it("returns error when line quantity is zero or negative", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [{ ...validLine, quantity: "0" }],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidQuantityError);
    }
  });

  it("returns error when item does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [validLine],
        },
        ctx,
        mockGetItemNotFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
  });

  it("returns error when item is not active", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [validLine],
        },
        ctx,
        mockGetItemInactive,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotActiveError);
    }
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [validLine],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StorageLocationNotFoundError);
    }
  });

  it("returns error when storage location is not active", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInactiveLocation]); // location found but INACTIVE

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [validLine],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StorageLocationNotActiveError);
    }
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [{ ...validLine, fromStockCategory: "AVAILABLE" as const }],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidFromStockCategoryError);
    }
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [{ ...validLine, lotId: "nonexistent-lot" }],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(LotNotFoundError);
    }
    // touch the fixture to keep it used if referenced elsewhere
    void baseActiveLot;
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "test", adjustmentDate },
          lines: [{ ...validLine, serialNumberId: "nonexistent-serial" }],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SerialNotFoundError);
    }
    void baseAvailableSerial;
  });

  it("creates stock adjustment in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStorageLocation], // location found
      [baseDraftAdjustment], // StockAdjustment insert
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "CORRECTION", reasonCode: "inventory-count", adjustmentDate },
          lines: [validLine],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(
      expectOk<{ stockAdjustment: { status: string } }>(result as never).stockAdjustment.status,
    ).toBe("DRAFT");
    expect(mock.inserts[1].insertRows()).toHaveLength(1);
  });

  it("accepts SCRAP type with fromStockCategory=BLOCKED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStorageLocation], // location found
      [{ ...baseDraftAdjustment, adjustmentType: "SCRAP" }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { adjustmentType: "SCRAP", reasonCode: "expired", adjustmentDate },
          lines: [
            {
              itemId: "item-1",
              storageLocationId: "location-1",
              quantity: "3",
              fromStockCategory: "BLOCKED",
            },
          ],
        },
        ctx,
        mockGetItemFound,
      ),
    );
    expect(result.ok).toBe(true);
  });
});
