import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment]);

    const result = await mock.withTx((trx) => run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const rejected = {
      ...baseSubmittedAdjustment,
      status: "REJECTED",
      rejectionReason: "insufficient documentation",
    };

    mock.enqueueResults([baseSubmittedAdjustment], [rejected]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({
        status: "REJECTED",
        rejectionReason: "insufficient documentation",
      }),
    );
  });

  it("succeeds without rejection reason", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const rejected = {
      ...baseSubmittedAdjustment,
      status: "REJECTED",
      rejectionReason: null,
    };

    mock.enqueueResults([baseSubmittedAdjustment], [rejected]);

    const result = await mock.withTx((trx) => run(trx, { 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();
    }
  });
});
