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

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

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

    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 COMPLETED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompletedCount);

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

  it("returns error when already cancelled", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelledCount = { ...basePlannedCount, status: "CANCELLED" };
    spies.select.mockReturnValueOnce(cancelledCount);

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

  it("cancels PLANNED count", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelledCount = { ...basePlannedCount, status: "CANCELLED", isFrozen: false };

    spies.select.mockReturnValueOnce(basePlannedCount);
    spies.delete.mockReturnValue(undefined); // delete count lines
    spies.update.mockReturnValue(cancelledCount);

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

  it("cancels IN_PROGRESS count", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelledCount = { ...baseInProgressCount, status: "CANCELLED", isFrozen: false };

    spies.select.mockReturnValueOnce(baseInProgressCount);
    spies.delete.mockReturnValue(undefined);
    spies.update.mockReturnValue(cancelledCount);

    const result = await run(db, { inventoryCountId: "count-2" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.inventoryCount.status).toBe("CANCELLED");
    }
  });

  it("unfreezes stock movements when count had frozen them", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const frozenCount = { ...baseInProgressCount, isFrozen: true };
    const cancelledCount = { ...frozenCount, status: "CANCELLED", isFrozen: false };

    spies.select.mockReturnValueOnce(frozenCount);
    spies.delete.mockReturnValue(undefined);
    spies.update.mockReturnValue(cancelledCount);

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

  it("discards count line data", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelledCount = { ...baseInProgressCount, status: "CANCELLED", isFrozen: false };

    spies.select.mockReturnValueOnce(baseInProgressCount);
    spies.delete.mockReturnValue(undefined);
    spies.update.mockReturnValue(cancelledCount);

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