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")

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

    // Get artist info with real data
    const artistResult = await sql`
      SELECT * FROM artists WHERE id = ${artistId}
    `
    const artist = artistResult[0]

    if (!artist) {
      return NextResponse.json({ error: "Artist not found" }, { status: 404 })
    }

    // Get tracks count
    const tracksResult = await sql`
      SELECT COUNT(*) as count FROM tracks WHERE artist_id = ${artistId}
    `

    // Get albums count
    const albumsResult = await sql`
      SELECT COUNT(*) as count FROM albums WHERE artist_id = ${artistId}
    `

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

    // Get followers count (real data)
    const followersResult = await sql`
      SELECT COUNT(*) as count FROM artist_followers WHERE artist_id = ${artistId}
    `

    const monthlyListenersResult = 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}
      AND lh.played_at > NOW() - INTERVAL '30 days'
    `

    // Get top tracks with real stream counts
    const topTracksResult = await sql`
      SELECT id, title, cover_url, total_streams, duration_ms
      FROM tracks 
      WHERE artist_id = ${artistId}
      ORDER BY total_streams DESC NULLS LAST
      LIMIT 5
    `

    const recentActivityResult = await sql`
      SELECT 
        t.title as description,
        COUNT(*) as value,
        MAX(lh.played_at) as created_at
      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 t.id, t.title
      ORDER BY MAX(lh.played_at) DESC
      LIMIT 10
    `

    const earningsResult = await sql`
      SELECT COALESCE(SUM(earnings_amount), 0) as total
      FROM artist_earnings
      WHERE artist_id = ${artistId}
    `

    return NextResponse.json({
      artist,
      stats: {
        totalTracks: Number.parseInt(tracksResult[0]?.count || "0"),
        totalAlbums: Number.parseInt(albumsResult[0]?.count || "0"),
        totalStreams: Number.parseInt(streamsResult[0]?.total || "0"),
        followers: Number.parseInt(followersResult[0]?.count || "0"),
        monthlyListeners: Number.parseInt(monthlyListenersResult[0]?.count || "0"),
        totalEarnings: Number.parseInt(earningsResult[0]?.total || "0"),
      },
      topTracks: topTracksResult.map((track) => ({
        ...track,
        play_count: track.total_streams || 0,
      })),
      recentActivity: recentActivityResult.map((activity) => ({
        description: activity.description,
        value: Number(activity.value),
        created_at: activity.created_at,
      })),
    })
  } catch (error) {
    console.error("Error fetching artist stats:", error)
    return NextResponse.json({ error: "Failed to fetch stats" }, { status: 500 })
  }
}
