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

// Server-side proxy for Tenor GIF search.
// Keeps the API key in env vars (TENOR_API_KEY) instead of shipping it to clients.
// Set TENOR_API_KEY in Vercel env. Without it, this endpoint returns an empty list.

export const runtime = 'edge';
export const dynamic = 'force-dynamic';

export async function GET(req: NextRequest) {
  const q = req.nextUrl.searchParams.get('q') || '';
  if (!q.trim()) {
    return NextResponse.json({ results: [] });
  }
  const key = process.env.TENOR_API_KEY;
  if (!key) {
    return NextResponse.json(
      { results: [], error: 'gif_search_unavailable' },
      { status: 200, headers: { 'cache-control': 'public, max-age=60' } }
    );
  }
  try {
    const url = `https://tenor.googleapis.com/v2/search?q=${encodeURIComponent(q)}&key=${key}&limit=12&media_filter=gif,tinygif`;
    const r = await fetch(url, { next: { revalidate: 60 } });
    if (!r.ok) {
      return NextResponse.json({ results: [] }, { status: 200 });
    }
    const data = await r.json();
    const results = (data.results || []).map((g: { media_formats?: { gif?: { url?: string }; tinygif?: { url?: string } } }) => ({
      url: g.media_formats?.gif?.url || '',
      preview: g.media_formats?.tinygif?.url || g.media_formats?.gif?.url || '',
    })).filter((g: { url: string }) => g.url);
    return NextResponse.json(
      { results },
      { headers: { 'cache-control': 'public, max-age=60' } }
    );
  } catch {
    return NextResponse.json({ results: [] }, { status: 200 });
  }
}
