import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { runDnsVerification } from '@/lib/services/dns-service'
import { processAutomation } from '@/lib/services/automation-worker'

/**
 * POST /api/v1/admin/orders/[id]/dns/verify
 * Trigger DNS verification for an order
 */
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: orderId } = await params

    // Run DNS verification
    const result = await runDnsVerification(orderId)

    // Process automation (will auto-trigger next step if in AUTO mode)
    const automationResult = await processAutomation(orderId)

    return NextResponse.json({
      success: true,
      verification: result,
      automation: automationResult,
    })
  } catch (error) {
    console.error('Error verifying DNS:', error)

    if (error instanceof Error) {
      if (error.message === 'Order not found') {
        return NextResponse.json({ error: 'Order not found' }, { status: 404 })
      }
      if (error.message === 'Server IP not configured') {
        return NextResponse.json(
          { error: 'Server IP not configured. Please add server credentials first.' },
          { status: 400 }
        )
      }
    }

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