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]
// Get container details
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

  // 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 container = await portainerClient.getContainer(containerId)
    const stats = await portainerClient.getContainerStats(containerId)

    return NextResponse.json({
      id: container.Id,
      name: container.Name.replace(/^\//, ''),
      image: container.Image,
      created: container.Created,
      state: container.State,
      config: {
        hostname: container.Config.Hostname,
        env: container.Config.Env,
        image: container.Config.Image,
        workingDir: container.Config.WorkingDir,
      },
      hostConfig: {
        restartPolicy: container.HostConfig.RestartPolicy,
      },
      networkSettings: {
        networks: container.NetworkSettings.Networks,
        ports: container.NetworkSettings.Ports,
      },
      stats,
    })
  } catch (error) {
    console.error('Failed to get container:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to get container' },
      { status: 500 }
    )
  }
}

// DELETE /api/v1/admin/enterprise-clients/[id]/servers/[serverId]/containers/[containerId]
// Remove a container
export async function DELETE(
  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 force = searchParams.get('force') === 'true'

  // 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 {
    await portainerClient.removeContainer(containerId, force)
    return NextResponse.json({
      success: true,
      message: 'Container removed successfully',
    })
  } catch (error) {
    console.error('Failed to remove container:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to remove container' },
      { status: 500 }
    )
  }
}

// POST /api/v1/admin/enterprise-clients/[id]/servers/[serverId]/containers/[containerId]
// Perform container action (start, stop, restart)
export async function POST(
  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 body = await request.json()
  const action = body.action as 'start' | 'stop' | 'restart'

  if (!['start', 'stop', 'restart'].includes(action)) {
    return NextResponse.json(
      { error: 'Invalid action. Must be one of: start, stop, restart' },
      { status: 400 }
    )
  }

  // 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 {
    switch (action) {
      case 'start':
        await portainerClient.startContainer(containerId)
        break
      case 'stop':
        await portainerClient.stopContainer(containerId)
        break
      case 'restart':
        await portainerClient.restartContainer(containerId)
        break
    }

    return NextResponse.json({
      success: true,
      message: `Container ${action} successful`,
    })
  } catch (error) {
    console.error(`Failed to ${action} container:`, error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : `Failed to ${action} container` },
      { status: 500 }
    )
  }
}
