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

export async function GET() {
  try {
    // Get comprehensive stats from database
    const [
      totalUsers,
      totalArtists,
      totalTracks,
      totalAlbums,
      totalStreams,
      premiumUsers,
      activeUsers,
      newUsersThisMonth,
      totalRevenue,
    ] = await Promise.all([
      sql`SELECT COUNT(*) as count FROM users WHERE is_active = true`,
      sql`SELECT COUNT(*) as count FROM artists`,
      sql`SELECT COUNT(*) as count FROM tracks WHERE status = 'published'`,
      sql`SELECT COUNT(*) as count FROM albums WHERE status = 'published'`,
      sql`SELECT COALESCE(SUM(total_streams), 0) as total FROM tracks`,
      sql`SELECT COUNT(*) as count FROM users WHERE subscription_type != 'free' AND is_active = true`,
      sql`SELECT COUNT(DISTINCT user_id) as count FROM listening_history WHERE played_at > NOW() - INTERVAL '7 days'`,
      sql`SELECT COUNT(*) as count FROM users WHERE created_at > DATE_TRUNC('month', NOW())`,
      sql`SELECT COALESCE(SUM(amount), 0) as total FROM payment_transactions WHERE status = 'completed'`,
    ])

    return NextResponse.json({
      stats: {
        totalUsers: Number.parseInt(totalUsers[0].count),
        totalArtists: Number.parseInt(totalArtists[0].count),
        totalTracks: Number.parseInt(totalTracks[0].count),
        totalAlbums: Number.parseInt(totalAlbums[0].count),
        totalStreams: Number.parseInt(totalStreams[0].total),
        premiumUsers: Number.parseInt(premiumUsers[0].count),
        activeUsers: Number.parseInt(activeUsers[0].count),
        newUsersThisMonth: Number.parseInt(newUsersThisMonth[0].count),
        totalRevenue: Number.parseInt(totalRevenue[0].total),
      },
    })
  } catch (error) {
    console.error("Stats error:", error)
    return NextResponse.json({ error: "Erreur lors de la récupération des statistiques" }, { status: 500 })
  }
}
