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

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

const powerActionSchema = z.object({
  action: z.literal('power'),
  command: z.enum(['ON', 'OFF', 'POWERCYCLE', 'RESET', 'POWEROFF'])
})

const verifiedActionSchema = z.object({
  action: z.enum(['wipe', 'reinstall']),
  verificationCode: z.string().length(6, 'Verification code must be 6 digits'),
  imageId: z.string().optional() // Required for reinstall
})

const actionSchema = z.discriminatedUnion('action', [
  powerActionSchema,
  verifiedActionSchema.extend({ action: z.literal('wipe') }),
  verifiedActionSchema.extend({ action: z.literal('reinstall'), imageId: z.string() })
])

/**
 * POST /api/v1/admin/enterprise-clients/[id]/servers/[serverId]/actions
 * Perform server action (power control or verified wipe/reinstall)
 */
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 {
    const body = await request.json()
    const validation = actionSchema.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 server = await enterpriseClientService.getServer(clientId, serverId)
    if (!server) {
      return NextResponse.json({ error: 'Server not found' }, { status: 404 })
    }

    const data = validation.data

    // Handle power actions (no verification needed)
    if (data.action === 'power') {
      await netcupService.powerAction(server.netcupServerId, data.command)
      return NextResponse.json({
        success: true,
        message: `Power action ${data.command} initiated`
      })
    }

    // Handle verified actions (wipe/reinstall)
    if (data.action === 'wipe' || data.action === 'reinstall') {
      // Verify the code
      const verifyResult = await securityVerificationService.verifyCode(
        clientId,
        data.verificationCode
      )

      if (!verifyResult.valid) {
        return NextResponse.json(
          { error: verifyResult.errorMessage || 'Invalid verification code' },
          { status: 400 }
        )
      }

      // Ensure the code was for the correct action and server
      if (verifyResult.action?.toLowerCase() !== data.action) {
        return NextResponse.json(
          { error: 'Verification code was issued for a different action' },
          { status: 400 }
        )
      }

      if (verifyResult.serverId !== serverId) {
        return NextResponse.json(
          { error: 'Verification code was issued for a different server' },
          { status: 400 }
        )
      }

      // Execute the action
      if (data.action === 'reinstall' && 'imageId' in data) {
        const task = await netcupService.reinstallServer(
          server.netcupServerId,
          data.imageId
        )
        return NextResponse.json({
          success: true,
          message: 'Server reinstall initiated',
          taskId: task.taskId
        })
      } else if (data.action === 'wipe') {
        // Wipe is essentially a reinstall with the same image
        // First get available images
        const images = await netcupService.getImageFlavours(server.netcupServerId)
        const defaultImage = images.find(img => img.name.toLowerCase().includes('debian')) || images[0]

        if (!defaultImage) {
          return NextResponse.json(
            { error: 'No image available for wipe operation' },
            { status: 400 }
          )
        }

        const task = await netcupService.reinstallServer(
          server.netcupServerId,
          defaultImage.id
        )
        return NextResponse.json({
          success: true,
          message: 'Server wipe initiated',
          taskId: task.taskId
        })
      }
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 })
  } catch (error) {
    console.error('Failed to execute server action:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to execute action' },
      { status: 500 }
    )
  }
}
