import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { netcupService, NetcupAuthError, NetcupApiError } from '@/lib/services/netcup-service'

/**
 * GET /api/v1/admin/netcup/servers
 * Get list of all Netcup servers
 *
 * Query params:
 * - liveInfo: "true" to load live status (ON/OFF) for each server (slower)
 */
export async function GET(request: NextRequest) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Check if authenticated
    const isAuth = await netcupService.isAuthenticated()
    if (!isAuth) {
      return NextResponse.json(
        { error: 'Not authenticated with Netcup. Please connect your account first.' },
        { status: 401 }
      )
    }

    // Check for liveInfo query parameter
    const searchParams = request.nextUrl.searchParams
    const loadLiveInfo = searchParams.get('liveInfo') === 'true'

    const servers = await netcupService.getServers(loadLiveInfo)

    return NextResponse.json({
      servers,
      count: servers.length,
    })
  } catch (error) {
    console.error('Error getting Netcup servers:', error)

    if (error instanceof NetcupAuthError) {
      return NextResponse.json(
        { error: error.message },
        { status: 401 }
      )
    }

    if (error instanceof NetcupApiError) {
      return NextResponse.json(
        { error: error.message },
        { status: error.statusCode }
      )
    }

    return NextResponse.json(
      { error: 'Failed to get servers' },
      { status: 500 }
    )
  }
}
