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

/**
 * POST /api/v1/admin/orders/[id]/dns/skip
 * Skip DNS verification with manual override (staff only)
 *
 * This allows staff to bypass DNS verification when they know
 * DNS is configured correctly but checks are failing (e.g., DNS propagation delay).
 */
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

    // Skip DNS verification
    await skipDnsVerification(orderId)

    // Get updated status
    const status = await getDnsStatus(orderId)

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

    return NextResponse.json({
      success: true,
      message: 'DNS verification skipped via manual override',
      status,
      automation: automationResult,
    })
  } catch (error) {
    console.error('Error skipping DNS verification:', error)

    if (error instanceof Error && error.message === 'Order not found') {
      return NextResponse.json({ error: 'Order not found' }, { status: 404 })
    }

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