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

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

  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 DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSubmittedAdjustment]);

    const result = await mock.withTx((trx) => run(trx, { id: "adjustment-2" }, ctx));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusError);
    }
  });

  it("returns error when already cancelled", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseCancelledAdjustment]);

    const result = await mock.withTx((trx) => run(trx, { id: "adjustment-5" }, ctx));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusError);
    }
  });

  it("transitions stock adjustment from DRAFT to CANCELLED", async () => {
    const cancelled = { ...baseDraftAdjustment, status: "CANCELLED" };

    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftAdjustment], [cancelled]);

    const result = await mock.withTx((trx) => run(trx, { id: "adjustment-1" }, ctx));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("CANCELLED");
    }
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ status: "CANCELLED" }),
    );
  });
});
