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

/**
 * GET /api/v1/admin/netcup/servers/[id]
 * Get server details
 *
 * Query params:
 * - liveInfo=true: Include live CPU/RAM/disk usage
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

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

    const { id: serverId } = await params
    const searchParams = request.nextUrl.searchParams
    const loadLiveInfo = searchParams.get('liveInfo') === 'true'

    const server = await netcupService.getServer(serverId, loadLiveInfo)

    return NextResponse.json(server)
  } catch (error) {
    console.error('Error getting Netcup server:', 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 server' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/v1/admin/netcup/servers/[id]
 * Perform action on server
 *
 * Body:
 * - action: 'power' | 'reinstall' | 'rescue' | 'hostname' | 'nickname'
 * - powerAction?: 'ON' | 'OFF' | 'POWERCYCLE' | 'RESET' | 'POWEROFF'
 * - imageFlavour?: string (for reinstall)
 * - rescueAction?: 'activate' | 'deactivate' (for rescue)
 * - hostname?: string (for hostname update)
 * - nickname?: string (for nickname update)
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

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

    const { id: serverId } = await params
    const body = await request.json()

    const { action, powerAction, imageFlavour, rescueAction, hostname, nickname } = body as {
      action: 'power' | 'reinstall' | 'rescue' | 'hostname' | 'nickname' | 'imageFlavours'
      powerAction?: PowerAction
      imageFlavour?: string
      rescueAction?: 'activate' | 'deactivate'
      hostname?: string
      nickname?: string
    }

    if (!action) {
      return NextResponse.json(
        { error: 'Action required' },
        { status: 400 }
      )
    }

    switch (action) {
      case 'power': {
        if (!powerAction || !['ON', 'OFF', 'POWERCYCLE', 'RESET', 'POWEROFF'].includes(powerAction)) {
          return NextResponse.json(
            { error: 'Valid powerAction required: ON, OFF, POWERCYCLE, RESET, POWEROFF' },
            { status: 400 }
          )
        }

        await netcupService.powerAction(serverId, powerAction)

        return NextResponse.json({
          success: true,
          message: `Power action ${powerAction} executed`,
        })
      }

      case 'reinstall': {
        if (!imageFlavour) {
          return NextResponse.json(
            { error: 'imageFlavour required for reinstall' },
            { status: 400 }
          )
        }

        const task = await netcupService.reinstallServer(serverId, imageFlavour)

        return NextResponse.json({
          success: true,
          message: 'Reinstall started',
          taskId: task.taskId,
        })
      }

      case 'rescue': {
        if (!rescueAction || !['activate', 'deactivate'].includes(rescueAction)) {
          return NextResponse.json(
            { error: 'rescueAction required: activate or deactivate' },
            { status: 400 }
          )
        }

        if (rescueAction === 'activate') {
          const credentials = await netcupService.activateRescue(serverId)
          return NextResponse.json({
            success: true,
            message: 'Rescue mode activated',
            credentials,
          })
        } else {
          await netcupService.deactivateRescue(serverId)
          return NextResponse.json({
            success: true,
            message: 'Rescue mode deactivated',
          })
        }
      }

      case 'hostname': {
        if (!hostname) {
          return NextResponse.json(
            { error: 'hostname required' },
            { status: 400 }
          )
        }

        await netcupService.updateHostname(serverId, hostname)

        return NextResponse.json({
          success: true,
          message: 'Hostname updated',
        })
      }

      case 'nickname': {
        if (nickname === undefined) {
          return NextResponse.json(
            { error: 'nickname required' },
            { status: 400 }
          )
        }

        await netcupService.updateNickname(serverId, nickname)

        return NextResponse.json({
          success: true,
          message: 'Nickname updated',
        })
      }

      case 'imageFlavours': {
        const flavours = await netcupService.getImageFlavours(serverId)
        return NextResponse.json({
          success: true,
          flavours,
        })
      }

      default:
        return NextResponse.json(
          { error: 'Invalid action' },
          { status: 400 }
        )
    }
  } catch (error) {
    console.error('Error performing Netcup server action:', 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 perform server action' },
      { status: 500 }
    )
  }
}
