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

// GET /api/v1/admin/enterprise-clients/[id]/servers/[serverId]/containers
// List all containers for a server
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; serverId: string }> }
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, serverId } = await params
  const { searchParams } = new URL(request.url)
  const all = searchParams.get('all') !== 'false' // Default to showing all containers

  // Verify server belongs to client
  const server = await prisma.enterpriseServer.findFirst({
    where: {
      id: serverId,
      clientId,
    },
  })

  if (!server) {
    return NextResponse.json(
      { error: 'Server not found' },
      { status: 404 }
    )
  }

  // Check if Portainer is configured
  const portainerClient = await createPortainerClientForServer(serverId)
  if (!portainerClient) {
    return NextResponse.json(
      { error: 'Portainer not configured for this server' },
      { status: 400 }
    )
  }

  try {
    // List containers
    const containers = await portainerClient.listContainers(all)

    // Get stats for running containers
    const stats = await portainerClient.getAllContainerStats()

    // Combine containers with stats
    const containersWithStats = containers.map(container => ({
      id: container.Id,
      names: container.Names.map(n => n.replace(/^\//, '')), // Remove leading slash
      image: container.Image,
      imageId: container.ImageID,
      command: container.Command,
      created: container.Created,
      state: container.State,
      status: container.Status,
      ports: container.Ports,
      labels: container.Labels,
      networks: container.NetworkSettings?.Networks || {},
      stats: stats[container.Id] || null,
    }))

    return NextResponse.json({
      serverId,
      containers: containersWithStats,
      total: containersWithStats.length,
      running: containersWithStats.filter(c => c.state === 'running').length,
      stopped: containersWithStats.filter(c => c.state !== 'running').length,
    })
  } catch (error) {
    console.error('Failed to list containers:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to list containers' },
      { status: 500 }
    )
  }
}
