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

export async function GET(request: NextRequest) {
  const url = request.nextUrl.searchParams.get('url');
  
  if (!url) {
    return new NextResponse('Missing url parameter', { status: 400 });
  }

  try {
    const res = await fetch(url, {
      headers: {
        // Use a generic user agent
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
      }
    });
    
    if (!res.ok) {
      console.error('Failed to proxy instagram image:', res.status, res.statusText);
      return new NextResponse('Failed to fetch image', { status: res.status });
    }

    const buffer = await res.arrayBuffer();
    
    const headers = new Headers();
    headers.set('Content-Type', res.headers.get('Content-Type') || 'image/jpeg');
    headers.set('Cache-Control', 'public, max-age=86400, s-maxage=86400');

    return new NextResponse(buffer, { headers });
  } catch (error) {
    console.error('Error in instagram proxy:', error);
    return new NextResponse('Error fetching image', { status: 500 });
  }
}
