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 "./approveInventoryAdjustment";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  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("approves adjustment", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...basePendingApprovalAdjustment, status: "APPROVED" };
    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("APPROVED");
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
