import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { apiKeyService } from '@/lib/services/api-key-service'

interface RegisterRequest {
  registrationToken: string
  orchestratorUrl?: string
  agentVersion?: string
}

/**
 * POST /api/v1/orchestrator/register
 * Called by Orchestrators to register with the Hub after deployment
 */
export async function POST(request: NextRequest) {
  try {
    const body: RegisterRequest = await request.json()

    // Validate required fields
    if (!body.registrationToken) {
      return NextResponse.json(
        { error: 'Missing required field: registrationToken' },
        { status: 400 }
      )
    }

    // Find the server connection by registration token
    const serverConnection = await prisma.serverConnection.findUnique({
      where: { registrationToken: body.registrationToken },
      include: {
        order: {
          include: {
            user: {
              select: { email: true, name: true },
            },
          },
        },
      },
    })

    if (!serverConnection) {
      return NextResponse.json(
        { error: 'Invalid registration token' },
        { status: 401 }
      )
    }

    // Check if already registered
    if (serverConnection.status !== 'PENDING') {
      return NextResponse.json(
        {
          error: 'Server already registered',
          status: serverConnection.status,
        },
        { status: 409 }
      )
    }

    // Generate Hub API key for this server (store hash, return plaintext once)
    const hubApiKey = apiKeyService.generateKey()
    const hubApiKeyHash = apiKeyService.hashKey(hubApiKey)

    // Update server connection with registration info
    const updatedConnection = await prisma.serverConnection.update({
      where: { id: serverConnection.id },
      data: {
        hubApiKey,
        hubApiKeyHash,
        orchestratorUrl: body.orchestratorUrl || null,
        agentVersion: body.agentVersion || null,
        status: 'REGISTERED',
        registeredAt: new Date(),
        lastHeartbeat: new Date(),
      },
    })

    // Update the order status if needed
    if (serverConnection.order.status === 'PROVISIONING') {
      await prisma.order.update({
        where: { id: serverConnection.orderId },
        data: {
          status: 'FULFILLED',
          completedAt: new Date(),
        },
      })

      // Log the successful registration
      await prisma.provisioningLog.create({
        data: {
          orderId: serverConnection.orderId,
          level: 'INFO',
          message: 'Orchestrator registered successfully with Hub',
          step: 'register',
        },
      })
    }

    return NextResponse.json({
      success: true,
      hubApiKey,
      message: 'Registration successful',
      serverId: updatedConnection.id,
      domain: serverConnection.order.domain,
    })
  } catch (error) {
    console.error('Registration error:', error)
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    )
  }
}
