import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CountNotFoundError, CountNotPlannedError } from "../lib/errors.generated";
import {
  basePlannedCount,
  baseInProgressCount,
  baseStockLevel,
  emptyStockLevel,
  baseZone,
} from "../testing/fixtures";
import { run } from "./startInventoryCount";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("returns error when not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // count lookup

    const result = await run(db, { inventoryCountId: "nonexistent" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CountNotFoundError);
    }
  });

  it("returns error when not planned", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInProgressCount); // count is IN_PROGRESS

    const result = await run(db, { inventoryCountId: "count-2" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CountNotPlannedError);
    }
  });

  it("starts count and snapshots quantities", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCount = { ...basePlannedCount, status: "IN_PROGRESS", isFrozen: false };

    spies.select
      .mockReturnValueOnce(basePlannedCount) // count lookup
      .mockReturnValueOnce([baseZone]) // locations for warehouse
      .mockReturnValueOnce([baseStockLevel]); // stock levels
    spies.insert.mockReturnValue({ id: "count-line-new" }); // count line insert
    spies.update.mockReturnValue(updatedCount); // status update

    const result = await run(db, { inventoryCountId: "count-1" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.inventoryCount.status).toBe("IN_PROGRESS");
    }
    expect(spies.insert).toHaveBeenCalled();
    expect(spies.update).toHaveBeenCalled();
  });

  it("creates count lines for all items at location", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const stockLevel2 = { ...emptyStockLevel, id: "stock-level-2", itemId: "item-2" };
    const updatedCount = { ...basePlannedCount, status: "IN_PROGRESS", isFrozen: false };

    spies.select
      .mockReturnValueOnce(basePlannedCount) // count lookup
      .mockReturnValueOnce([baseZone]) // locations for warehouse
      .mockReturnValueOnce([baseStockLevel, stockLevel2]); // stock levels
    spies.insert
      .mockReturnValueOnce({ id: "count-line-1" })
      .mockReturnValueOnce({ id: "count-line-2" });
    spies.update.mockReturnValue(updatedCount);

    const result = await run(db, { inventoryCountId: "count-1" }, ctx);
    expect(result.ok).toBe(true);
    expect(spies.insert).toHaveBeenCalledTimes(2);
  });

  it("optionally freezes stock movements", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedCount = { ...basePlannedCount, status: "IN_PROGRESS", isFrozen: true };

    spies.select
      .mockReturnValueOnce(basePlannedCount) // count lookup
      .mockReturnValueOnce([baseZone]) // locations for warehouse
      .mockReturnValueOnce([baseStockLevel]); // stock levels
    spies.insert.mockReturnValue({ id: "count-line-new" });
    spies.update.mockReturnValue(updatedCount);

    const result = await run(db, { inventoryCountId: "count-1", freeze: true }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.inventoryCount.isFrozen).toBe(true);
    }
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ isFrozen: true }));
  });
});
