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/[containerId]/logs
// Get container logs
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; serverId: string; containerId: string }> }
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, serverId, containerId } = await params
  const { searchParams } = new URL(request.url)
  const tail = parseInt(searchParams.get('tail') || '500', 10)

  // 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 }
    )
  }

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

  try {
    const logs = await portainerClient.getContainerLogs(containerId, tail)

    return NextResponse.json({
      containerId,
      tail,
      logs,
      timestamp: new Date().toISOString(),
    })
  } 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 }
    )
  }
}
