import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

// GET /api/admin/ringtone-api/logs - Get API usage logs with filtering
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const operatorId = searchParams.get("operator")
    const startDate = searchParams.get("start_date")
    const endDate = searchParams.get("end_date")
    const endpoint = searchParams.get("endpoint")
    const status = searchParams.get("status")
    const limit = Number.parseInt(searchParams.get("limit") || "100")
    const offset = Number.parseInt(searchParams.get("offset") || "0")

    const conditions = []
    const params: any[] = []

    if (operatorId) {
      conditions.push(`api_key_id = $${params.length + 1}`)
      params.push(operatorId)
    }

    if (startDate) {
      conditions.push(`created_at >= $${params.length + 1}`)
      params.push(startDate)
    }

    if (endDate) {
      conditions.push(`created_at <= $${params.length + 1}`)
      params.push(endDate)
    }

    if (endpoint) {
      conditions.push(`endpoint LIKE $${params.length + 1}`)
      params.push(`%${endpoint}%`)
    }

    if (status) {
      conditions.push(`status_code = $${params.length + 1}`)
      params.push(Number.parseInt(status))
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""

    const logs = await sql`
      SELECT 
        l.*,
        k.name as api_name,
        k.company
      FROM api_usage_logs l
      LEFT JOIN external_api_keys k ON k.id = l.api_key_id
      ${sql.unsafe(whereClause)}
      ORDER BY l.created_at DESC
      LIMIT ${limit}
      OFFSET ${offset}
    `

    const [countResult] = await sql`
      SELECT COUNT(*) as total
      FROM api_usage_logs
      ${sql.unsafe(whereClause)}
    `

    return NextResponse.json({
      success: true,
      data: logs,
      meta: {
        total: countResult.total,
        limit,
        offset,
      },
    })
  } catch (error) {
    console.error("Error fetching API logs:", error)
    return NextResponse.json({ error: "Failed to fetch logs" }, { status: 500 })
  }
}
