import type { NextRequest } from "next/server"
import { safeQuery } from "@/lib/db"
import { successResponse, errorResponse } from "@/lib/api-response"

export const runtime = "nodejs"

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { trackId, userId, durationMs } = body

    if (!trackId) {
      return errorResponse("Missing trackId")
    }

    // Record listening event (non-blocking, never fails)
    await safeQuery`
      INSERT INTO listening_history (track_id, user_id, duration_ms)
      VALUES (${trackId}, ${userId || null}, ${durationMs || 0})
    `

    return successResponse({ recorded: true })
  } catch (error) {
    console.error("[Analytics] Error recording:", error)
    // Never block audio streaming, return success even on error
    return successResponse({ recorded: false })
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const trackId = searchParams.get("trackId")
    const period = searchParams.get("period") || "7d"

    let dateFilter = ""
    if (period === "24h") {
      dateFilter = "AND created_at > NOW() - INTERVAL '24 hours'"
    } else if (period === "7d") {
      dateFilter = "AND created_at > NOW() - INTERVAL '7 days'"
    } else if (period === "30d") {
      dateFilter = "AND created_at > NOW() - INTERVAL '30 days'"
    }

    if (trackId) {
      // Get specific track analytics
      const stats = await safeQuery<{
        total_streams: number
        unique_listeners: number
        avg_duration_ms: number
      }>`
        SELECT 
          COUNT(*) as total_streams,
          COUNT(DISTINCT user_id) as unique_listeners,
          AVG(duration_ms) as avg_duration_ms
        FROM listening_history
        WHERE track_id = ${trackId}
        ${dateFilter ? dateFilter : ""}
      `

      return successResponse(stats[0] || { total_streams: 0, unique_listeners: 0, avg_duration_ms: 0 })
    }

    // Get overall analytics
    const totalStreams = await safeQuery<{ count: number }>`
      SELECT COUNT(*) as count FROM listening_history
      WHERE 1=1 ${dateFilter ? dateFilter : ""}
    `

    const activeUsers = await safeQuery<{ count: number }>`
      SELECT COUNT(DISTINCT user_id) as count FROM listening_history
      WHERE user_id IS NOT NULL ${dateFilter ? dateFilter : ""}
    `

    const topTracks = await safeQuery<{
      track_id: number
      title: string
      streams: number
    }>`
      SELECT 
        lh.track_id,
        t.title,
        COUNT(*) as streams
      FROM listening_history lh
      JOIN tracks t ON t.id = lh.track_id
      WHERE 1=1 ${dateFilter ? dateFilter : ""}
      GROUP BY lh.track_id, t.title
      ORDER BY streams DESC
      LIMIT 10
    `

    const streamsPerDay = await safeQuery<{
      date: string
      streams: number
    }>`
      SELECT 
        DATE(created_at) as date,
        COUNT(*) as streams
      FROM listening_history
      WHERE created_at > NOW() - INTERVAL '30 days'
      GROUP BY DATE(created_at)
      ORDER BY date DESC
    `

    return successResponse({
      totalStreams: totalStreams[0]?.count || 0,
      activeUsers: activeUsers[0]?.count || 0,
      topTracks: topTracks || [],
      streamsPerDay: streamsPerDay || [],
    })
  } catch (error) {
    console.error("[Analytics] Error fetching:", error)
    return successResponse({
      totalStreams: 0,
      activeUsers: 0,
      topTracks: [],
      streamsPerDay: [],
    })
  }
}
