const RESET_CONFIRMATION = "delete_code_remote_manager_data";

export async function resolveApplicationDataRoute(req, url, context) {
  if (req.method !== "DELETE" || url.pathname !== "/application-data") return null;
  const input = await context.readJson(req);
  if (input?.confirmation !== RESET_CONFIRMATION) throw routeError("application_data_confirmation_required", 400);
  if (!context.managedHost) throw routeError("application_data_restart_unavailable", 409);

  let prepared = false;
  context.beginReset?.();
  try {
    await context.prepareSessions?.();
    prepared = true;
    context.stopRuntime?.();
    const result = await context.deleteData();
    context.expirePairing?.();
    context.requestRestart?.();
    return { status: 202, body: { reset: { scheduled: true, pendingCleanup: result.pendingCleanup ?? 0 } } };
  } catch (error) {
    if (prepared) context.requestRestart?.();
    else context.endReset?.();
    if (["application_data_in_use", "application_data_cleanup_required", "application_data_reset_failed"].includes(error?.message)) throw error;
    throw routeError("application_data_reset_failed", 500);
  }
}

function routeError(code, status) {
  const error = new Error(code);
  error.status = status;
  error.safeLogCode = code;
  return error;
}
