import { describe, expect, it, vi } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidMovementTypeError,
  EmptyMoveLinesError,
  ItemNotFoundError,
  ItemNotActiveError,
  InvalidQuantityError,
  SameSourceDestinationError,
  StorageLocationNotFoundError,
  ReasonCodeRequiredError,
  LotRequiredForTrackedItemError,
} from "../lib/errors.generated";
import { baseZone, baseBin } from "../testing/fixtures";
import { run } from "./createStockMovement";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const activeItem = { id: "item-1", status: "ACTIVE", isLotTracked: false };
  const inactiveItem = { id: "item-2", status: "DRAFT", isLotTracked: false };
  const lotTrackedItem = { id: "item-3", status: "ACTIVE", isLotTracked: true };

  const makeGetItem = (items: Record<string, unknown>) => ({
    getItem: vi.fn().mockImplementation((_db: unknown, input: { id: string }) => {
      const item = items[input.id] ?? null;
      return Promise.resolve({ ok: true, value: { item } });
    }),
  });

  it("returns error when invalid movement type", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeGetItem({});

    const result = await run(
      db,
      {
        movementType: "INVALID_TYPE",
        lines: [{ itemId: "item-1", quantity: 10 }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidMovementTypeError);
    }
  });

  it("returns error when no move lines", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeGetItem({});

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(EmptyMoveLinesError);
    }
  });

  it("returns error when item not found", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeGetItem({}); // no items

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [{ itemId: "nonexistent", quantity: 10, destinationLocationId: "location-1" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
  });

  it("returns error when item not active", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-2": inactiveItem });

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [{ itemId: "item-2", quantity: 10, destinationLocationId: "location-1" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotActiveError);
    }
  });

  it("returns error when quantity is zero or negative", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-1": activeItem });

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [{ itemId: "item-1", quantity: 0, destinationLocationId: "location-1" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidQuantityError);
    }
  });

  it("returns error when source equals destination", async () => {
    const { db } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-1": activeItem });

    const result = await run(
      db,
      {
        movementType: "INTERNAL_TRANSFER",
        lines: [
          {
            itemId: "item-1",
            quantity: 10,
            sourceLocationId: "location-1",
            destinationLocationId: "location-1",
          },
        ],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SameSourceDestinationError);
    }
  });

  it("returns error when storage location not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-1": activeItem });
    spies.select.mockReturnValueOnce(undefined); // destination location not found

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [{ itemId: "item-1", quantity: 10, destinationLocationId: "nonexistent" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StorageLocationNotFoundError);
    }
  });

  it("returns error when block without reason code", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-1": activeItem });
    spies.select.mockReturnValueOnce(baseZone); // source location lookup

    const result = await run(
      db,
      {
        movementType: "BLOCK",
        lines: [
          {
            itemId: "item-1",
            quantity: 5,
            sourceLocationId: "location-1",
          },
        ],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ReasonCodeRequiredError);
    }
  });

  it("creates movement in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-1": activeItem });
    spies.select.mockReturnValueOnce(baseZone); // destination location lookup

    const createdMovement = {
      id: "movement-new",
      movementType: "GOODS_RECEIPT",
      reasonCode: null,
      status: "DRAFT",
      executedAt: null,
      createdAt: new Date(),
      updatedAt: null,
    };
    const createdLine = {
      id: "line-new",
      stockMovementId: "movement-new",
      itemId: "item-1",
      quantity: 10,
      sourceLocationId: null,
      destinationLocationId: "location-1",
      lotId: null,
      serialNumberId: null,
      createdAt: new Date(),
      updatedAt: null,
    };

    spies.insert.mockReturnValueOnce(createdMovement).mockReturnValueOnce(createdLine);

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [{ itemId: "item-1", quantity: 10, destinationLocationId: "location-1" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockMovement.status).toBe("DRAFT");
      expect(result.value.stockMoveLines).toHaveLength(1);
    }
  });

  it("returns error when lot-tracked item has no lotId", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-3": lotTrackedItem });
    spies.select.mockReturnValueOnce(baseZone); // destination location lookup

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [{ itemId: "item-3", quantity: 5, destinationLocationId: "location-1" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(LotRequiredForTrackedItemError);
    }
  });

  it("creates movement with multiple lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const queries = makeGetItem({ "item-1": activeItem });
    // Two destination location lookups
    spies.select.mockReturnValueOnce(baseZone).mockReturnValueOnce(baseBin);

    const createdMovement = {
      id: "movement-new",
      movementType: "GOODS_RECEIPT",
      reasonCode: null,
      status: "DRAFT",
      executedAt: null,
      createdAt: new Date(),
      updatedAt: null,
    };
    const createdLine1 = {
      id: "line-1",
      stockMovementId: "movement-new",
      itemId: "item-1",
      quantity: 10,
      sourceLocationId: null,
      destinationLocationId: "location-1",
      lotId: null,
      serialNumberId: null,
      createdAt: new Date(),
      updatedAt: null,
    };
    const createdLine2 = {
      id: "line-2",
      stockMovementId: "movement-new",
      itemId: "item-1",
      quantity: 20,
      sourceLocationId: null,
      destinationLocationId: "location-2",
      lotId: null,
      serialNumberId: null,
      createdAt: new Date(),
      updatedAt: null,
    };

    spies.insert
      .mockReturnValueOnce(createdMovement)
      .mockReturnValueOnce(createdLine1)
      .mockReturnValueOnce(createdLine2);

    const result = await run(
      db,
      {
        movementType: "GOODS_RECEIPT",
        lines: [
          { itemId: "item-1", quantity: 10, destinationLocationId: "location-1" },
          { itemId: "item-1", quantity: 20, destinationLocationId: "location-2" },
        ],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockMoveLines).toHaveLength(2);
    }
    expect(spies.insert).toHaveBeenCalledTimes(3); // 1 movement + 2 lines
  });
});
