import { cancelDeviceRelease } from "../../../db/devices";

/**
 * POST /api/devices/:id/cancel-release
 *
 * User zieht einen offenen Release-Request zurück.
 * Setzt release_requested_at zurück auf NULL — Lock bleibt aktiv.
 *
 * Auth: eingeloggter User, ownership-check via userId im DB-Query.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event, { skipDeviceCheck: true });
  const id = getRouterParam(event, "id");

  if (!id) {
    throw createError({ statusCode: 400, data: { error: "MISSING_ID" } });
  }

  const updated = await cancelDeviceRelease(user.id, id);

  if (!updated) {
    throw createError({
      statusCode: 404,
      data: { error: "DEVICE_NOT_FOUND_OR_NO_PENDING_RELEASE" },
    });
  }

  return { success: true };
});
