import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import https from 'https'

/**
 * GET /api/v1/admin/portainer/ping
 * Check if Portainer is reachable at a given IP
 *
 * Query params:
 * - ip: Server IP address
 * - port: Portainer port (default: 9443)
 */
export async function GET(request: NextRequest) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const searchParams = request.nextUrl.searchParams
    const ip = searchParams.get('ip')
    const port = searchParams.get('port') || '9443'

    if (!ip) {
      return NextResponse.json(
        { error: 'IP address required' },
        { status: 400 }
      )
    }

    // Validate IP format (basic check)
    const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$/
    if (!ipRegex.test(ip)) {
      return NextResponse.json(
        { error: 'Invalid IP address format' },
        { status: 400 }
      )
    }

    // Use native https module to handle self-signed certificates
    const result = await new Promise<{ available: boolean; version?: string; instanceId?: string | null; needsSetup?: boolean; error?: string }>((resolve) => {
      const req = https.request(
        {
          hostname: ip,
          port: parseInt(port),
          path: '/api/status',
          method: 'GET',
          timeout: 5000,
          rejectUnauthorized: false, // Accept self-signed certificates
        },
        (res) => {
          let data = ''
          res.on('data', (chunk) => {
            data += chunk
          })
          res.on('end', () => {
            if (res.statusCode === 200) {
              try {
                const json = JSON.parse(data)
                // InstanceID is only set after Portainer has been initialized
                // (admin account created). If it's empty, Portainer is running
                // but not configured yet.
                const isInitialized = !!json.InstanceID
                resolve({
                  available: isInitialized,
                  version: json.Version || 'unknown',
                  instanceId: json.InstanceID || null,
                  needsSetup: !isInitialized,
                })
              } catch {
                resolve({
                  available: false,
                  version: 'unknown',
                  error: 'Failed to parse response',
                })
              }
            } else {
              resolve({
                available: false,
                error: `Portainer returned status ${res.statusCode}`,
              })
            }
          })
        }
      )

      req.on('error', (err) => {
        resolve({
          available: false,
          error: err.message,
        })
      })

      req.on('timeout', () => {
        req.destroy()
        resolve({
          available: false,
          error: 'Connection timed out',
        })
      })

      req.end()
    })

    return NextResponse.json(result)
  } catch (error) {
    console.error('Error checking Portainer status:', error)
    return NextResponse.json(
      { error: 'Failed to check Portainer status' },
      { status: 500 }
    )
  }
}
