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 {
  StockReservationNotFoundError,
  StockReservationNotOpenError,
} from "../lib/errors.generated";
import { baseStockReservation } from "../testing/fixtures";
import { run } from "./closeStockReservation";

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

  const input = {
    id: "stock-reservation-1",
  };

  it("closes reservation by id", async () => {
    const closed = { ...baseStockReservation, status: "CLOSED" };

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

    const result = await mock.withTx((trx) => run(trx, input, ctx));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockReservation.status).toBe("CLOSED");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

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

    const result = await mock.withTx((trx) => run(trx, input, ctx));

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

  it("returns error when reservation is closed", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseStockReservation, status: "CLOSED" }]);

    const result = await mock.withTx((trx) => run(trx, input, ctx));

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