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 }>
}

const addServerSchema = z.object({
  netcupServerId: z.string().min(1, 'Netcup server ID is required'),
  nickname: z.string().optional(),
  purpose: z.string().optional(),
  portainerUrl: z.string().url().optional(),
  portainerUsername: z.string().optional(),
  portainerPassword: z.string().optional()
})

/**
 * GET /api/v1/admin/enterprise-clients/[id]/servers
 * List all servers for an enterprise client with live status from Netcup
 */
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 } = await context.params

  try {
    // Get client's servers from database
    const servers = await enterpriseClientService.getClientServers(clientId)

    // Enrich with live Netcup status if possible
    const enrichedServers = await Promise.all(
      servers.map(async (server) => {
        try {
          const netcupServer = await netcupService.getServer(server.netcupServerId, true)
          return {
            ...server,
            netcupStatus: netcupServer?.state || 'unknown',
            netcupHostname: netcupServer?.hostname,
            netcupIps: [netcupServer?.primaryIpv4, netcupServer?.primaryIpv6].filter(Boolean) as string[]
          }
        } catch {
          return {
            ...server,
            netcupStatus: 'error',
            netcupHostname: null,
            netcupIps: []
          }
        }
      })
    )

    return NextResponse.json(enrichedServers)
  } catch (error) {
    console.error('Failed to list servers:', error)
    return NextResponse.json(
      { error: 'Failed to list servers' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/v1/admin/enterprise-clients/[id]/servers
 * Add a server to an enterprise client
 */
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 } = await context.params

  try {
    const body = await request.json()
    const validation = addServerSchema.safeParse(body)

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

    // Verify client exists
    const client = await enterpriseClientService.getClient(clientId)
    if (!client) {
      return NextResponse.json({ error: 'Client not found' }, { status: 404 })
    }

    // Verify Netcup server exists
    try {
      const netcupServer = await netcupService.getServer(validation.data.netcupServerId)
      if (!netcupServer) {
        return NextResponse.json(
          { error: 'Netcup server not found' },
          { status: 400 }
        )
      }
    } catch (error) {
      return NextResponse.json(
        { error: 'Failed to verify Netcup server. Is Netcup connected?' },
        { status: 400 }
      )
    }

    const server = await enterpriseClientService.addServer(clientId, validation.data)
    return NextResponse.json(server, { status: 201 })
  } catch (error) {
    console.error('Failed to add server:', error)

    // Check for unique constraint violation
    if (error instanceof Error && error.message.includes('Unique constraint')) {
      return NextResponse.json(
        { error: 'This Netcup server is already linked to this client' },
        { status: 400 }
      )
    }

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