import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";

/**
 * GET /api/cache/entries?tier=exact&limit=50&offset=0&model=...
 *
 * Proxies to llmhosts backend cache entries endpoint.
 */
export async function GET(request: NextRequest) {
  try {
    const backendUrl =
      process.env.LLMHOSTS_BACKEND_URL || "http://llmhosts:4000";

    const { searchParams } = request.nextUrl;
    const tier = searchParams.get("tier") || "exact";
    const limit = searchParams.get("limit") || "50";
    const offset = searchParams.get("offset") || "0";
    const model = searchParams.get("model");

    const params = new URLSearchParams({ tier, limit, offset });
    if (model) params.set("model", model);

    const res = await fetch(
      `${backendUrl}/api/cache/entries?${params.toString()}`,
      { headers: { Accept: "application/json" } }
    );

    if (!res.ok) {
      logger.error({ action: 'cache_entries_fetch', status: res.status, statusText: res.statusText }, 'Failed to fetch cache entries');
      return NextResponse.json(
        { entries: [], total: 0, offset: 0, limit: 50 },
        { status: 200 }
      );
    }

    const data = await res.json();
    return NextResponse.json(data);
  } catch (error) {
    logger.error({ err: error, action: 'cache_entries_fetch' }, 'Error fetching cache entries');
    return NextResponse.json(
      { entries: [], total: 0, offset: 0, limit: 50 },
      { status: 200 }
    );
  }
}
