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

export async function GET(request: NextRequest) {
  try {
    const userId = request.nextUrl.searchParams.get("userId")

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

    const [likedCount, downloadCount, followedArtistsCount, recentCount, storageUsed] = await Promise.all([
      // Liked tracks count
      sql`SELECT COUNT(*) as count FROM liked_tracks WHERE user_id = ${userId}`,
      // Downloaded tracks count
      sql`SELECT COUNT(*) as count FROM downloaded_tracks WHERE user_id = ${userId}`,
      // Followed artists count
      sql`SELECT COUNT(*) as count FROM artist_followers WHERE user_id = ${userId}`,
      // Recently played count (unique tracks in last 30 days)
      sql`SELECT COUNT(DISTINCT track_id) as count FROM listening_history WHERE user_id = ${userId} AND played_at > NOW() - INTERVAL '30 days'`,
      // Storage used (sum of downloaded files size in bytes)
      sql`SELECT COALESCE(SUM(file_size_bytes), 0) as total FROM downloaded_tracks WHERE user_id = ${userId}`,
    ])

    // Convert bytes to GB
    const storageBytes = Number.parseInt(storageUsed[0]?.total || "0")
    const storageGB = Math.round((storageBytes / (1024 * 1024 * 1024)) * 100) / 100

    return NextResponse.json({
      likedTracks: Number.parseInt(likedCount[0]?.count || "0"),
      downloads: Number.parseInt(downloadCount[0]?.count || "0"),
      followedArtists: Number.parseInt(followedArtistsCount[0]?.count || "0"),
      recentlyPlayed: Number.parseInt(recentCount[0]?.count || "0"),
      storageUsedGB: storageGB,
      storageTotalGB: 64, // Default storage limit
    })
  } catch (error) {
    console.error("Library stats error:", error)
    return NextResponse.json({ error: "Erreur lors de la récupération des statistiques" }, { status: 500 })
  }
}
