import {
  normalizeRoute,
  recordApiRequest
} from "./chunk-D2XITRN6.js";
import {
  authenticateAndIntercept
} from "./chunk-3OWGP2RP.js";
import {
  checkAndBump
} from "./chunk-HVUWXUUI.js";
import {
  ensureInitialized
} from "./chunk-3CFYTKBL.js";
import {
  captureException
} from "./chunk-3MQ2FWXS.js";
import {
  ApiError,
  toResponse,
  tooManyRequests
} from "./chunk-EZYKRG4W.js";

// src/http.ts
async function routeWrap(request, handler) {
  const startedAt = Date.now();
  let status = 500;
  try {
    await ensureInitialized();
    const result = await authenticateAndIntercept(request);
    if (result.kind === "response") {
      status = result.response.status;
      return result.response;
    }
    const auth = result.auth;
    const retryAfter = await checkAndBump(auth.keyId, auth.rateLimitRpm);
    if (retryAfter != null) {
      const err = tooManyRequests(
        `rate limit exceeded (${auth.rateLimitRpm}/min for this key); retry after ${retryAfter}s`
      );
      const res2 = toResponse(err);
      const headers = new Headers(res2.headers);
      headers.set("Retry-After", String(retryAfter));
      status = 429;
      return new Response(res2.body, { status: 429, headers });
    }
    const res = await handler({ auth, request });
    status = res.status;
    return res;
  } catch (err) {
    if (!(err instanceof ApiError) || err.status >= 500) {
      captureException(err);
    }
    const res = toResponse(err);
    status = res.status;
    return res;
  } finally {
    try {
      const route = normalizeRoute(request.url);
      recordApiRequest(route, Date.now() - startedAt, status);
    } catch {
    }
  }
}
function jsonOk(body, status = 200) {
  return Response.json(body, { status });
}
function paginatedOk(data, requestedLimit) {
  const hasMore = data.length === requestedLimit;
  const firstId = data.length > 0 ? data[0].id : null;
  const lastId = data.length > 0 ? data[data.length - 1].id : null;
  return jsonOk({ data, has_more: hasMore, first_id: firstId, last_id: lastId });
}
function decodeCursor(page) {
  if (!page) return void 0;
  if (page.includes("_")) return page;
  try {
    return Buffer.from(page, "base64url").toString("utf8");
  } catch {
    return void 0;
  }
}

export {
  routeWrap,
  jsonOk,
  paginatedOk,
  decodeCursor
};
