import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { StockAdjustmentNotFoundError, InvalidStatusError } from "../lib/errors.generated";
import {
  baseDraftAdjustment,
  baseSubmittedAdjustment,
  baseCancelledAdjustment,
} from "../testing/fixtures";
import { run } from "./cancelStockAdjustment";

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

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

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

  it("returns error when stock adjustment is not in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSubmittedAdjustment);

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

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

    const result = await run(db, { id: "adjustment-5" }, ctx);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusError);
    }
  });

  it("transitions stock adjustment from DRAFT to CANCELLED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const cancelled = { ...baseDraftAdjustment, status: "CANCELLED" };

    spies.select.mockReturnValueOnce(baseDraftAdjustment);
    spies.update.mockReturnValue(cancelled);

    const result = await run(db, { id: "adjustment-1" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("CANCELLED");
    }
    expect(spies.set).toHaveBeenCalledWith(expect.objectContaining({ status: "CANCELLED" }));
  });
});
