import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { enterpriseClientService } from '@/lib/services/enterprise-client-service'
import { netcupService } from '@/lib/services/netcup-service'
import { z } from 'zod'

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

const updateServerSchema = z.object({
  nickname: z.string().optional().nullable(),
  purpose: z.string().optional().nullable(),
  isActive: z.boolean().optional(),
  portainerUrl: z.string().url().optional().nullable(),
  portainerUsername: z.string().optional().nullable(),
  portainerPassword: z.string().optional()
})

/**
 * GET /api/v1/admin/enterprise-clients/[id]/servers/[serverId]
 * Get server details with Netcup live info
 */
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

  try {
    const server = await enterpriseClientService.getServer(clientId, serverId)

    if (!server) {
      return NextResponse.json({ error: 'Server not found' }, { status: 404 })
    }

    // Get Netcup live info
    let netcupInfo = null
    try {
      netcupInfo = await netcupService.getServer(server.netcupServerId, true)
    } catch (error) {
      console.error('Failed to get Netcup server info:', error)
    }

    return NextResponse.json({
      ...server,
      netcup: netcupInfo
    })
  } catch (error) {
    console.error('Failed to get server:', error)
    return NextResponse.json(
      { error: 'Failed to get server' },
      { status: 500 }
    )
  }
}

/**
 * PATCH /api/v1/admin/enterprise-clients/[id]/servers/[serverId]
 * Update server
 */
export async function PATCH(
  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 {
    const body = await request.json()
    const validation = updateServerSchema.safeParse(body)

    if (!validation.success) {
      return NextResponse.json(
        { error: 'Validation failed', details: validation.error.flatten() },
        { status: 400 }
      )
    }

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

    const server = await enterpriseClientService.updateServer(serverId, validation.data)
    return NextResponse.json(server)
  } catch (error) {
    console.error('Failed to update server:', error)
    return NextResponse.json(
      { error: 'Failed to update server' },
      { status: 500 }
    )
  }
}

/**
 * DELETE /api/v1/admin/enterprise-clients/[id]/servers/[serverId]
 * Remove server from client (does not delete from Netcup)
 */
export async function DELETE(
  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 {
    // Check if server exists and belongs to client
    const existingServer = await enterpriseClientService.getServer(clientId, serverId)
    if (!existingServer) {
      return NextResponse.json({ error: 'Server not found' }, { status: 404 })
    }

    await enterpriseClientService.removeServer(clientId, serverId)
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Failed to remove server:', error)
    return NextResponse.json(
      { error: 'Failed to remove server' },
      { status: 500 }
    )
  }
}
