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 followers count
    const followersResult = await sql`
      SELECT COUNT(*) as count FROM artist_followers WHERE artist_id = ${artistId}
    `

    // Get new followers (last 7 days)
    const newFollowersResult = await sql`
      SELECT COUNT(*) as count 
      FROM artist_followers 
      WHERE artist_id = ${artistId}
      AND created_at >= NOW() - INTERVAL '7 days'
    `

    const countriesResult = await sql`
      SELECT COUNT(DISTINCT u.country) as count
      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}
      AND u.country IS NOT NULL
    `

    const topCountries = await sql`
      SELECT 
        COALESCE(u.country, 'Inconnu') as city,
        COUNT(DISTINCT lh.user_id) 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
    `

    const totalListenersResult = 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}
    `

    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'
    `

    const listeningTimesResult = await sql`
      SELECT 
        CASE 
          WHEN EXTRACT(HOUR FROM played_at) BETWEEN 6 AND 11 THEN 'morning'
          WHEN EXTRACT(HOUR FROM played_at) BETWEEN 12 AND 17 THEN 'afternoon'
          WHEN EXTRACT(HOUR FROM played_at) BETWEEN 18 AND 23 THEN 'evening'
          ELSE 'night'
        END as time_of_day,
        COUNT(*) as count
      FROM listening_history lh
      JOIN tracks t ON lh.track_id = t.id
      WHERE t.artist_id = ${artistId}
      GROUP BY time_of_day
    `

    // Calculate listening time percentages
    const totalListens = listeningTimesResult.reduce((acc, row) => acc + Number(row.count), 0)
    const listeningHabits = [
      { time: "Matin (6h-12h)", percentage: 0 },
      { time: "Apres-midi (12h-18h)", percentage: 0 },
      { time: "Soiree (18h-0h)", percentage: 0 },
      { time: "Nuit (0h-6h)", percentage: 0 },
    ]

    if (totalListens > 0) {
      listeningTimesResult.forEach((row) => {
        const percentage = Math.round((Number(row.count) / totalListens) * 100)
        if (row.time_of_day === "morning") listeningHabits[0].percentage = percentage
        else if (row.time_of_day === "afternoon") listeningHabits[1].percentage = percentage
        else if (row.time_of_day === "evening") listeningHabits[2].percentage = percentage
        else if (row.time_of_day === "night") listeningHabits[3].percentage = percentage
      })
    }

    const topTracksResult = await sql`
      SELECT 
        t.id,
        t.title,
        t.cover_url,
        t.total_streams,
        COUNT(DISTINCT lh.user_id) as unique_listeners
      FROM tracks t
      LEFT JOIN listening_history lh ON t.id = lh.track_id
      WHERE t.artist_id = ${artistId}
      GROUP BY t.id, t.title, t.cover_url, t.total_streams
      ORDER BY t.total_streams DESC NULLS LAST
      LIMIT 5
    `

    const recentFollowersResult = await sql`
      SELECT 
        u.id,
        u.name,
        u.avatar_url,
        af.created_at
      FROM artist_followers af
      JOIN users u ON af.user_id = u.id
      WHERE af.artist_id = ${artistId}
      ORDER BY af.created_at DESC
      LIMIT 10
    `

    return NextResponse.json({
      followers: Number.parseInt(followersResult[0]?.count || "0"),
      newFollowers: Number.parseInt(newFollowersResult[0]?.count || "0"),
      countries: Number.parseInt(countriesResult[0]?.count || "0"),
      totalListeners: Number.parseInt(totalListenersResult[0]?.count || "0"),
      monthlyListeners: Number.parseInt(monthlyListenersResult[0]?.count || "0"),
      topCities: topCountries.length > 0 ? topCountries : [],
      listeningHabits,
      topTracks: topTracksResult,
      recentFollowers: recentFollowersResult,
      // Default demographics (would need user profile data to be accurate)
      ageGroups: [
        { range: "13-17", percentage: 8 },
        { range: "18-24", percentage: 35 },
        { range: "25-34", percentage: 32 },
        { range: "35-44", percentage: 15 },
        { range: "45+", percentage: 10 },
      ],
      genderData: [
        { gender: "Femme", percentage: 54 },
        { gender: "Homme", percentage: 44 },
        { gender: "Autre", percentage: 2 },
      ],
    })
  } catch (error) {
    console.error("Error fetching audience:", error)
    return NextResponse.json({ error: "Failed to fetch audience" }, { status: 500 })
  }
}
