import { getAudioApi, getRateLimiter } from "@/lib/server/app-services";
import { clientAddress, rateLimitResponse } from "@/lib/server/rate-limit";

export async function GET(
  request: Request,
  context: { params: Promise<{ segmentId: string }> },
) {
  const { segmentId } = await context.params;
  const voice = new URL(request.url).searchParams.get("voice") ?? "";
  const metadataOnly = new URL(request.url).searchParams.get("describe") === "1";
  return metadataOnly
    ? getAudioApi().describe(segmentId, voice)
    : getAudioApi().stream(request, segmentId, voice);
}

export async function PUT(
  request: Request,
  context: { params: Promise<{ segmentId: string }> },
) {
  const limit = await getRateLimiter().consume("audio_upload", clientAddress(request), {
    limit: 240,
    windowSeconds: 60 * 60,
  });
  if (!limit.allowed) return rateLimitResponse(limit.retryAfterSeconds);
  const { segmentId } = await context.params;
  return getAudioApi().upload(request, segmentId);
}
