import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AdjustmentNotFoundError,
  AdjustmentNotPendingApprovalError,
} from "../lib/errors.generated";
import { basePendingApprovalAdjustment, baseDraftAdjustment } from "../testing/fixtures";
import { run } from "./rejectInventoryAdjustment";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  it("returns error when not found", 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(AdjustmentNotFoundError);
    }
  });

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

    const result = await run(db, { id: "adjustment-1" }, ctx);

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

  it("rejects adjustment", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...basePendingApprovalAdjustment, status: "REJECTED" };
    spies.select.mockReturnValueOnce(basePendingApprovalAdjustment);
    spies.update.mockReturnValue(updated);

    const result = await run(db, { id: "adjustment-2" }, ctx);

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

  it("rejected adjustment does not affect stock", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...basePendingApprovalAdjustment, status: "REJECTED" };
    spies.select.mockReturnValueOnce(basePendingApprovalAdjustment);
    spies.update.mockReturnValue(updated);

    await run(db, { id: "adjustment-2" }, ctx);

    // Only one update call (status change), no stock level or valuation updates
    expect(spies.update).toHaveBeenCalledTimes(1);
    expect(spies.insert).not.toHaveBeenCalled();
  });
});
