import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"

const TENOR_API_KEY = process.env.TENOR_API_KEY || ""
const TENOR_BASE = "https://tenor.googleapis.com/v2"

export async function GET(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { searchParams } = new URL(request.url)
    const q = searchParams.get("q") || ""
    const limit = Math.min(parseInt(searchParams.get("limit") || "20", 10), 50)
    const pos = searchParams.get("pos") || ""

    if (!TENOR_API_KEY) {
      return NextResponse.json({
        results: [],
        error: "TENOR_API_KEY not configured",
        noKey: true,
      })
    }

    const endpoint = q
      ? `${TENOR_BASE}/search?q=${encodeURIComponent(q)}&key=${TENOR_API_KEY}&limit=${limit}&media_filter=minimal`
      : `${TENOR_BASE}/featured?key=${TENOR_API_KEY}&limit=${limit}&media_filter=minimal`

    const url = pos ? `${endpoint}&pos=${pos}` : endpoint

    const res = await fetch(url, { signal: AbortSignal.timeout(8000) })
    if (!res.ok) {
      return NextResponse.json({ results: [], error: "Tenor API error" }, { status: 502 })
    }

    const data = await res.json()

    const results = (data.results || []).map((item: any) => {
      const media = item.media_formats?.gif || item.media_formats?.tinygif || {}
      const preview = item.media_formats?.tinygif || item.media_formats?.gif || {}
      return {
        id: item.id,
        title: item.title || "",
        url: media.url || "",
        previewUrl: preview.url || "",
        width: media.dims?.[0] || 200,
        height: media.dims?.[1] || 200,
      }
    })

    return NextResponse.json({ results, next: data.next || "" })
  } catch (error) {
    console.error("GIF API error:", error)
    return NextResponse.json({ results: [], error: "Failed to fetch GIFs" }, { status: 500 })
  }
}
