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]/logs
 * Get container logs
 * Query: ?tail=100 (number of lines)
 */
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
  const searchParams = request.nextUrl.searchParams
  const tail = parseInt(searchParams.get('tail') || '100', 10)

  try {
    const client = await createPortainerClient(orderId)

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

    const logs = await client.getContainerLogs(containerId, tail)

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