import { type NextRequest, NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const artistId = searchParams.get("artistId")
    const period = searchParams.get("period") || "7d"

    if (!artistId) {
      return NextResponse.json({ error: "Artist ID required" }, { status: 400 })
    }

    // Get streams over time from listening_history
    const streamsOverTime = await sql`
      SELECT 
        DATE(lh.played_at) as date,
        COUNT(*) as streams
      FROM listening_history lh
      JOIN tracks t ON lh.track_id = t.id
      WHERE t.artist_id = ${artistId}
      AND lh.played_at >= NOW() - INTERVAL '7 days'
      GROUP BY DATE(lh.played_at)
      ORDER BY date
    `

    // Get top tracks
    const topTracks = await sql`
      SELECT id, title, total_streams, cover_url
      FROM tracks
      WHERE artist_id = ${artistId}
      ORDER BY total_streams DESC
      LIMIT 5
    `

    // Get listener countries (from user locations)
    const topCountries = await sql`
      SELECT 
        COALESCE(u.country, 'Unknown') as country,
        COUNT(*) as listeners
      FROM listening_history lh
      JOIN tracks t ON lh.track_id = t.id
      JOIN users u ON lh.user_id = u.id
      WHERE t.artist_id = ${artistId}
      GROUP BY u.country
      ORDER BY listeners DESC
      LIMIT 5
    `

    // Get unique listeners
    const listenersResult = await sql`
      SELECT COUNT(DISTINCT lh.user_id) as count
      FROM listening_history lh
      JOIN tracks t ON lh.track_id = t.id
      WHERE t.artist_id = ${artistId}
    `

    // Get total streams
    const totalStreamsResult = await sql`
      SELECT COALESCE(SUM(total_streams), 0) as total
      FROM tracks
      WHERE artist_id = ${artistId}
    `

    return NextResponse.json({
      streamsOverTime:
        streamsOverTime.length > 0 ? streamsOverTime : [{ date: new Date().toISOString().split("T")[0], streams: 0 }],
      topTracks,
      topCountries: topCountries.length > 0 ? topCountries : [],
      totalStreams: Number.parseInt(totalStreamsResult[0]?.total || "0"),
      uniqueListeners: Number.parseInt(listenersResult[0]?.count || "0"),
    })
  } catch (error) {
    console.error("Error fetching analytics:", error)
    return NextResponse.json({ error: "Failed to fetch analytics" }, { status: 500 })
  }
}
