// ── AI: Giphy Integration ────────────────────────────────────────────────────
// GET /api/ai/giphy  — Proxy for GIPHY API (search or trending)
//
// Auth: authenticated
// Query params: type=search|trending, q=search query, offset, limit
// Returns a curated subset of GIF fields suitable for chat/UI integration.

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

// ── Constants ────────────────────────────────────────────────────────────────

const GIPHY_API_KEY = process.env.GIPHY_API_KEY
const GIPHY_BASE = "https://api.giphy.com/v1/gifs"

// ── GET ──────────────────────────────────────────────────────────────────────

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

    if (!GIPHY_API_KEY) {
      return NextResponse.json({ error: "GIPHY API key not configured" }, { status: 500 })
    }

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

    // Route to search or trending endpoint based on type param
    let url: string
    if (type === "search" && query) {
      url = `${GIPHY_BASE}/search?api_key=${GIPHY_API_KEY}&q=${encodeURIComponent(query)}&limit=${limit}&offset=${offset}&rating=g`
    } else {
      url = `${GIPHY_BASE}/trending?api_key=${GIPHY_API_KEY}&limit=${limit}&offset=${offset}&rating=g`
    }

    const res = await fetch(url)
    if (!res.ok) {
      const errBody = await res.text()
      console.error("GIPHY API error:", res.status, errBody)
      return NextResponse.json({ error: `GIPHY API error (${res.status}): ${errBody}` }, { status: res.status })
    }

    const data = await res.json()

    // Normalize the response to a minimal set of fields used by the UI
    const gifs = (data.data || []).map((gif: any) => ({
      id: gif.id,
      title: gif.title,
      url: gif.images?.original?.url || "",
      previewUrl: gif.images?.fixed_width?.url || "",
      previewHeight: gif.images?.fixed_width?.height || 150,
      width: gif.images?.original?.width || 0,
      height: gif.images?.original?.height || 0,
    }))

    return NextResponse.json({
      gifs,
      pagination: data.pagination || { total_count: 0, count: gifs.length, offset },
    })
  } catch (error: any) {
    console.error("GIPHY proxy error:", error)
    return NextResponse.json({ error: error.message || "Internal server error" }, { status: 500 })
  }
}
