import { describe, expect, it, vi } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  StockMovementNotFoundError,
  StockMovementNotDraftError,
  ItemNotActiveError,
  InvalidQuantityError,
  SameSourceDestinationError,
  StorageLocationNotFoundError,
} from "../lib/errors.generated";
import { baseDraftMovement, baseConfirmedMovement, baseZone } from "../testing/fixtures";
import { run } from "./updateStockMovement";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

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

  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 not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // movement not found
    const queries = makeGetItem({});

    const result = await run(db, { id: "nonexistent" }, ctx, queries);

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

  it("returns error when not in DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseConfirmedMovement);
    const queries = makeGetItem({});

    const result = await run(db, { id: baseConfirmedMovement.id }, ctx, queries);

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

  it("updates movement date", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, reasonCode: "new-reason", updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseDraftMovement);
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({});

    const result = await run(
      db,
      { id: baseDraftMovement.id, reasonCode: "new-reason" },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockMovement.reasonCode).toBe("new-reason");
    }
    expect(spies.update).toHaveBeenCalled();
  });

  it("returns error when line item not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseDraftMovement); // movement lookup
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({ "item-2": inactiveItem });

    const result = await run(
      db,
      {
        id: baseDraftMovement.id,
        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 line quantity is zero or negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseDraftMovement); // movement lookup
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({ "item-1": activeItem });

    const result = await run(
      db,
      {
        id: baseDraftMovement.id,
        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, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseDraftMovement); // movement lookup
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({ "item-1": activeItem });

    const result = await run(
      db,
      {
        id: baseDraftMovement.id,
        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 location not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, updatedAt: new Date() };
    spies.select
      .mockReturnValueOnce(baseDraftMovement) // movement lookup
      .mockReturnValueOnce(undefined); // destination location not found
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({ "item-1": activeItem });

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

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

  it("adds new move line", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, updatedAt: new Date() };
    spies.select
      .mockReturnValueOnce(baseDraftMovement) // movement lookup
      .mockReturnValueOnce(baseZone); // destination location lookup
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({ "item-1": activeItem });

    const newLine = {
      id: "line-new",
      stockMovementId: baseDraftMovement.id,
      itemId: "item-1",
      quantity: 30,
      sourceLocationId: null,
      destinationLocationId: "location-1",
      lotId: null,
      serialNumberId: null,
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.insert.mockReturnValueOnce(newLine);

    const result = await run(
      db,
      {
        id: baseDraftMovement.id,
        lines: [{ itemId: "item-1", quantity: 30, destinationLocationId: "location-1" }],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
      const value = result.value as any;
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      expect(value.stockMoveLines).toHaveLength(1);
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      expect(value.stockMoveLines![0].quantity).toBe(30);
    }
  });

  it("removes move line", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftMovement, updatedAt: new Date() };
    spies.select.mockReturnValueOnce(baseDraftMovement);
    spies.update.mockReturnValue(updated);
    const queries = makeGetItem({});

    // Provide empty lines array to replace all existing lines with none
    const result = await run(
      db,
      {
        id: baseDraftMovement.id,
        lines: [],
      },
      ctx,
      queries,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
      const value = result.value as any;
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      expect(value.stockMoveLines).toHaveLength(0);
    }
  });
});
