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

/**
 * POST /api/cache/invalidate
 *
 * Proxies to llmhosts backend cache invalidation endpoint.
 */
export async function POST(request: NextRequest) {
  try {
    const backendUrl =
      process.env.LLMHOSTS_BACKEND_URL || "http://llmhosts:4000";

    const body = await request.json();

    const res = await fetch(`${backendUrl}/api/cache/invalidate`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify(body),
    });

    if (!res.ok) {
      logger.error({ action: 'cache_invalidate', status: res.status, statusText: res.statusText }, 'Failed to invalidate cache');
      return NextResponse.json(
        { error: "Failed to invalidate cache" },
        { status: res.status }
      );
    }

    const data = await res.json();
    return NextResponse.json(data);
  } catch (error) {
    logger.error({ err: error, action: 'cache_invalidate' }, 'Error invalidating cache');
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
