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 [keysCount] = await sql`SELECT COUNT(*) as count FROM external_api_keys WHERE status = 'active'`
    const [downloadsCount] = await sql`SELECT COUNT(*) as count FROM ringtone_downloads`
    const [revenue] = await sql`SELECT COALESCE(SUM(price), 0) as total FROM ringtone_downloads`
    const [tracksCount] = await sql`SELECT COUNT(*) as count FROM tracks WHERE ringtone_enabled = true`

    return NextResponse.json({
      success: true,
      data: {
        totalKeys: Number.parseInt(keysCount.count),
        totalDownloads: Number.parseInt(downloadsCount.count),
        totalRevenue: Number.parseFloat(revenue.total),
        enabledTracks: Number.parseInt(tracksCount.count),
      },
    })
  } catch (error) {
    console.error("Error fetching stats:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
