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

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

  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 in REJECTED status", 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(AdjustmentNotRejectedError);
    }
  });

  it("transitions rejected adjustment back to DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseRejectedAdjustment, status: "DRAFT" };
    spies.select.mockReturnValueOnce(baseRejectedAdjustment);
    spies.update.mockReturnValue(updated);

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

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

  it("revised adjustment can be modified and resubmitted", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const revised = { ...baseRejectedAdjustment, status: "DRAFT" };
    spies.select.mockReturnValueOnce(baseRejectedAdjustment);
    spies.update.mockReturnValue(revised);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      // After revise, adjustment is back in DRAFT and can be modified/resubmitted
      expect(result.value.inventoryAdjustment.status).toBe("DRAFT");
    }
  });
});
