import { approveRequest } from "../../../../db/device-approvals";
import { findUserDevice } from "../../../../db/devices";

/**
 * POST /api/devices/approvals/:id/approve
 *
 * Aufgerufen von einem EXISTIERENDEN Gerät (mit x-device-id Header).
 * Body: { evictDeviceRowId?: string }
 *
 * Wenn der User am Limit ist, MUSS der Client einen evictDeviceRowId mitschicken
 * (das Gerät das ersetzt wird). Der Endpoint löscht atomar den UserDevice +
 * markiert Approval als approved. Das NEUE Gerät kann danach `register` neu
 * aufrufen — der Slot ist frei.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const id = getRouterParam(event, "id");
  if (!id) {
    throw createError({ statusCode: 400, message: "id required" });
  }

  const body = (await readBody(event).catch(() => ({}))) as {
    evictDeviceRowId?: string;
  };

  // Map approving deviceId → UserDevice.id für Audit-Log
  const approvingDeviceId = getHeader(event, "x-device-id");
  let approvingRowId: string | null = null;
  if (approvingDeviceId) {
    const row = await findUserDevice(user.id, approvingDeviceId);
    approvingRowId = row?.id ?? null;
  }

  const approval = await approveRequest({
    approvalId: id,
    userId: user.id,
    approvedByDeviceRowId: approvingRowId,
    evictDeviceRowId: body.evictDeviceRowId ?? null,
  });

  if (!approval) {
    throw createError({ statusCode: 404, message: "approval not found" });
  }
  if (approval.status !== "approved") {
    throw createError({
      statusCode: 409,
      message: `approval is ${approval.status}`,
      data: { approval },
    });
  }
  return { approval };
});
