import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { enterpriseClientService } from '@/lib/services/enterprise-client-service'
import { statsCollectionService } from '@/lib/services/stats-collection-service'
import type { StatsRange } from '@/lib/services/stats-collection-service'

interface RouteContext {
  params: Promise<{ id: string; serverId: string }>
}

/**
 * GET /api/v1/admin/enterprise-clients/[id]/servers/[serverId]/stats
 * Get stats history for a server
 */
export async function GET(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, serverId } = await context.params
  const searchParams = request.nextUrl.searchParams
  const range = (searchParams.get('range') || '24h') as StatsRange

  try {
    // Verify server belongs to client
    const server = await enterpriseClientService.getServer(clientId, serverId)
    if (!server) {
      return NextResponse.json({ error: 'Server not found' }, { status: 404 })
    }

    const [history, latest] = await Promise.all([
      statsCollectionService.getServerStatsHistory(serverId, range),
      statsCollectionService.getServerLatestStats(serverId)
    ])

    return NextResponse.json({
      serverId,
      range,
      latest,
      history,
      dataPoints: history.length
    })
  } catch (error) {
    console.error('Failed to get server stats:', error)
    return NextResponse.json(
      { error: 'Failed to get server stats' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/v1/admin/enterprise-clients/[id]/servers/[serverId]/stats
 * Trigger manual stats collection for a server
 */
export async function POST(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, serverId } = await context.params

  try {
    // Verify server belongs to client
    const server = await enterpriseClientService.getServer(clientId, serverId)
    if (!server) {
      return NextResponse.json({ error: 'Server not found' }, { status: 404 })
    }

    const snapshot = await statsCollectionService.collectServerStats(serverId)

    if (!snapshot) {
      return NextResponse.json(
        { error: 'Failed to collect stats' },
        { status: 500 }
      )
    }

    return NextResponse.json({
      success: true,
      message: 'Stats collected successfully',
      snapshot: {
        id: snapshot.id,
        timestamp: snapshot.timestamp,
        cpuPercent: snapshot.cpuPercent,
        memoryUsedMb: snapshot.memoryUsedMb,
        memoryTotalMb: snapshot.memoryTotalMb,
        diskReadMbps: snapshot.diskReadMbps,
        diskWriteMbps: snapshot.diskWriteMbps,
        networkInMbps: snapshot.networkInMbps,
        networkOutMbps: snapshot.networkOutMbps
      }
    })
  } catch (error) {
    console.error('Failed to collect server stats:', error)
    return NextResponse.json(
      { error: 'Failed to collect stats' },
      { status: 500 }
    )
  }
}
