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

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

/**
 * GET /api/v1/admin/orders/[id]/containers
 * List all containers for an order's Portainer instance
 * Query: ?all=true (include stopped containers)
 */
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 } = await context.params
  const searchParams = request.nextUrl.searchParams
  const all = searchParams.get('all') !== 'false' // Default to true

  try {
    const client = await createPortainerClient(orderId)

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

    const containers = await client.listContainers(all)

    // Transform to a simpler format for the frontend
    const formattedContainers = containers.map((c) => ({
      id: c.Id,
      shortId: c.Id.substring(0, 12),
      name: c.Names[0]?.replace(/^\//, '') || c.Id.substring(0, 12),
      image: c.Image,
      state: c.State,
      status: c.Status,
      created: c.Created,
      ports: c.Ports.map((p) => ({
        private: p.PrivatePort,
        public: p.PublicPort,
        type: p.Type,
      })),
    }))

    return NextResponse.json(formattedContainers)
  } catch (error) {
    console.error('Failed to list containers:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to list containers' },
      { status: 500 }
    )
  }
}
