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 {
  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 { db, spies } = createMockDb<Transaction>();
    const closed = { ...baseStockReservation, status: "CLOSED" };

    spies.select.mockReturnValueOnce(baseStockReservation);
    spies.update.mockReturnValue(closed);

    const result = await run(db, input, ctx);

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

  it("returns error when reservation not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, input, ctx);

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

  it("returns error when reservation is closed", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseStockReservation, status: "CLOSED" });

    const result = await run(db, input, ctx);

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