import { NextRequest, NextResponse } from 'next/server';

/**
 * Medya dosyalarını backend'den proxy eden API route.
 * Docker konteyner içinde INTERNAL_API_URL üzerinden backend'e ulaşır.
 * Tarayıcı /media/... isteklerini bu route üzerinden yönlendirir.
 *
 * URL formatı: /api/media/[projectId]/images/[filename]
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  const { path } = await params;
  const mediaPath = path.join('/');

  // Docker içinde backend internal URL, yoksa localhost
  const internalUrl = process.env.INTERNAL_API_URL;
  const backendBase = internalUrl
    ? internalUrl.replace(/\/api$/, '')
    : 'http://localhost:3000';

  const targetUrl = `${backendBase}/media/${mediaPath}`;

  try {
    const response = await fetch(targetUrl);

    if (!response.ok) {
      return new NextResponse(null, { status: response.status });
    }

    const buffer = await response.arrayBuffer();
    const contentType = response.headers.get('content-type') || 'application/octet-stream';

    return new NextResponse(buffer, {
      status: 200,
      headers: {
        'Content-Type': contentType,
        'Cache-Control': 'public, max-age=86400, immutable',
        'Cross-Origin-Resource-Policy': 'cross-origin',
      },
    });
  } catch (error) {
    console.error(`Media proxy error: ${targetUrl}`, error);
    return new NextResponse(null, { status: 502 });
  }
}
