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

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

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

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

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

  it("submits for approval", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftAdjustment, status: "PENDING_APPROVAL" };
    spies.select.mockReturnValueOnce(baseDraftAdjustment);
    spies.update.mockReturnValue(updated);

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

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