import { safeQuery } from "@/lib/db"
import { successResponse } from "@/lib/api-response"

export const runtime = "nodejs"

export async function GET() {
  try {
    const streamsResult = await safeQuery<{ total_streams: number }>`
      SELECT COUNT(*) as total_streams FROM listening_history
    `

    const usersResult = await safeQuery<{ total: number }>`
      SELECT COUNT(DISTINCT user_id) as total 
      FROM listening_history 
      WHERE created_at > NOW() - INTERVAL '30 days'
    `

    const newTracksResult = await safeQuery<{ total: number }>`
      SELECT COUNT(*) as total FROM tracks WHERE created_at > NOW() - INTERVAL '30 days'
    `

    const topTracks = await safeQuery<{ title: string; artist: string; streams: number }>`
      SELECT t.title, a.name as artist, COUNT(*) as streams
      FROM listening_history lh
      JOIN tracks t ON t.id = lh.track_id
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE lh.created_at > NOW() - INTERVAL '30 days'
      GROUP BY t.title, a.name
      ORDER BY streams DESC
      LIMIT 5
    `

    const streamsByMonth = await safeQuery<{ month: string; streams: number }>`
      SELECT 
        TO_CHAR(created_at, 'Mon') as month,
        COUNT(*) as streams
      FROM listening_history
      WHERE created_at > NOW() - INTERVAL '12 months'
      GROUP BY TO_CHAR(created_at, 'Mon'), DATE_TRUNC('month', created_at)
      ORDER BY DATE_TRUNC('month', created_at)
    `

    return successResponse({
      totalStreams: streamsResult[0]?.total_streams || 0,
      activeUsers: usersResult[0]?.total || 0,
      newTracks: newTracksResult[0]?.total || 0,
      topTracks: topTracks || [],
      streamsByMonth: streamsByMonth || [],
    })
  } catch (error) {
    console.error("[Admin Analytics] Error:", error)
    return successResponse({
      totalStreams: 0,
      activeUsers: 0,
      newTracks: 0,
      topTracks: [],
      streamsByMonth: [],
    })
  }
}
