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

export async function GET(request: NextRequest) {
  const userId = await getAdminUser(request)
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  try {
    const { searchParams } = new URL(request.url)
    const operatorId = searchParams.get("operator")
    const phone = searchParams.get("phone")
    const msisdn = searchParams.get("msisdn")
    const limit = Math.min(Number.parseInt(searchParams.get("limit") || "50"), 200)
    const offset = Number.parseInt(searchParams.get("offset") || "0")

    let downloads

    if (phone || msisdn) {
      const searchPhone = phone || msisdn
      downloads = await sql`
        SELECT 
          rd.*,
          t.title as track_title,
          t.cover_url,
          a.name as artist_name,
          k.name as api_name,
          k.company as operator_company
        FROM ringtone_downloads rd
        LEFT JOIN tracks t ON rd.track_id = t.id
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN external_api_keys k ON rd.api_key_id = k.id
        WHERE (rd.customer_phone ILIKE ${"%" + searchPhone + "%"} 
               OR rd.customer_msisdn ILIKE ${"%" + searchPhone + "%"})
        ORDER BY rd.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else if (operatorId) {
      downloads = await sql`
        SELECT 
          rd.*,
          t.title as track_title,
          t.cover_url,
          a.name as artist_name,
          k.name as api_name,
          k.company as operator_company
        FROM ringtone_downloads rd
        LEFT JOIN tracks t ON rd.track_id = t.id
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN external_api_keys k ON rd.api_key_id = k.id
        WHERE rd.api_key_id = ${operatorId}
        ORDER BY rd.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else {
      downloads = await sql`
        SELECT 
          rd.*,
          t.title as track_title,
          t.cover_url,
          a.name as artist_name,
          k.name as api_name,
          k.company as operator_company
        FROM ringtone_downloads rd
        LEFT JOIN tracks t ON rd.track_id = t.id
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN external_api_keys k ON rd.api_key_id = k.id
        ORDER BY rd.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    }

    const [countResult] = await sql`SELECT COUNT(*) as total FROM ringtone_downloads`

    const [stats] = await sql`
      SELECT 
        COUNT(*) as total_downloads,
        COUNT(DISTINCT customer_phone) as unique_customers,
        COALESCE(SUM(price), 0) as total_revenue,
        COUNT(DISTINCT api_key_id) as operators_count
      FROM ringtone_downloads
    `

    return NextResponse.json({
      success: true,
      data: downloads,
      stats: {
        totalDownloads: Number.parseInt(stats.total_downloads),
        uniqueCustomers: Number.parseInt(stats.unique_customers),
        totalRevenue: Number.parseFloat(stats.total_revenue),
        operatorsCount: Number.parseInt(stats.operators_count),
      },
      meta: {
        total: Number.parseInt(countResult.total),
        limit,
        offset,
      },
    })
  } catch (error) {
    console.error("Error fetching downloads:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
