import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ReasonCodeRequiredError,
  EmptyAdjustmentLinesError,
  InvalidQuantityError,
  ItemNotFoundError,
  ItemNotActiveError,
  StorageLocationNotFoundError,
  StorageLocationNotActiveError,
  InvalidFromStockCategoryError,
  LotNotFoundError,
  SerialNotFoundError,
} from "../lib/errors.generated";
import { mockItemManagementQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseDraftAdjustment,
  correctionIncreaseLine,
  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 { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      { 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 { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      { 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 { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      {
        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 { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      { 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 { db } = createMockDb<Transaction>();
    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // location not found

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactiveLocation); // location found but INACTIVE

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseStorageLocation); // location found

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseStorageLocation) // location found
      .mockReturnValueOnce(undefined); // lot not found

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseStorageLocation) // location found
      .mockReturnValueOnce(undefined); // serial not found

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseStorageLocation); // location found
    spies.insert
      .mockReturnValueOnce(baseDraftAdjustment) // StockAdjustment insert
      .mockReturnValueOnce([correctionIncreaseLine]); // StockAdjustmentLine bulk insert

    const result = await run(
      db,
      {
        adjustmentType: "CORRECTION",
        reasonCode: "inventory-count",
        adjustmentDate,
        lines: [validLine],
      },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("DRAFT");
      expect(result.value.stockAdjustmentLines).toHaveLength(1);
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("accepts SCRAP type with fromStockCategory=BLOCKED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseStorageLocation); // location found
    spies.insert
      .mockReturnValueOnce({ ...baseDraftAdjustment, adjustmentType: "SCRAP" })
      .mockReturnValueOnce([
        {
          ...correctionIncreaseLine,
          fromStockCategory: "BLOCKED",
          adjustmentDirection: null,
        },
      ]);

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