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 } from "../testing/fixtures";
import { run } from "./rejectStockAdjustment";

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

  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 SUBMITTED 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(InvalidStatusError);
    }
  });

  it("transitions stock adjustment from SUBMITTED to REJECTED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rejected = {
      ...baseSubmittedAdjustment,
      status: "REJECTED",
      rejectionReason: "insufficient documentation",
    };

    spies.select.mockReturnValueOnce(baseSubmittedAdjustment);
    spies.update.mockReturnValue(rejected);

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

  it("succeeds without rejection reason", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const rejected = {
      ...baseSubmittedAdjustment,
      status: "REJECTED",
      rejectionReason: null,
    };

    spies.select.mockReturnValueOnce(baseSubmittedAdjustment);
    spies.update.mockReturnValue(rejected);

    const result = await run(db, { id: "adjustment-2" }, ctx);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("REJECTED");
      expect(result.value.stockAdjustment.rejectionReason).toBeNull();
    }
  });
});
