import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { createPortainerClient } from '@/lib/services/portainer-client'

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

/**
 * GET /api/v1/admin/orders/[id]/containers/[containerId]/stats
 * Get stats for a single container
 */
export async function GET(
  request: NextRequest,
  context: RouteContext
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: orderId, containerId } = await context.params

  try {
    const client = await createPortainerClient(orderId)

    if (!client) {
      return NextResponse.json(
        { error: 'Portainer credentials not configured for this order' },
        { status: 400 }
      )
    }

    const stats = await client.getContainerStats(containerId)

    if (!stats) {
      return NextResponse.json(
        { error: 'Container not running or stats unavailable' },
        { status: 404 }
      )
    }

    return NextResponse.json(stats)
  } catch (error) {
    console.error('Failed to get container stats:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to get container stats' },
      { status: 500 }
    )
  }
}
