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

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

  const activeItem = { id: "item-1", status: "ACTIVE", isLotTracked: false };
  const inactiveItem = { id: "item-1", 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);
    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 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("returns error when no move lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftMovement) // movement lookup
      .mockReturnValueOnce([]); // empty lines
    const queries = makeGetItem({});

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

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

  it("returns error when item not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftMovement) // movement lookup
      .mockReturnValueOnce([baseMoveLine]); // lines
    const queries = makeGetItem({ "item-1": inactiveItem });

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

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

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

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

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

  it("confirms valid movement", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const confirmed = { ...baseDraftMovement, status: "CONFIRMED", updatedAt: new Date() };
    spies.select
      .mockReturnValueOnce(baseDraftMovement) // movement lookup
      .mockReturnValueOnce([baseMoveLine]) // lines
      .mockReturnValueOnce(baseZone); // destination location lookup
    spies.update.mockReturnValue(confirmed);
    const queries = makeGetItem({ "item-1": activeItem });

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockMovement.status).toBe("CONFIRMED");
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
