import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { containerHealthService } from '@/lib/services/container-health-service'
import type { ContainerEventType } from '@prisma/client'

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

  const { id: clientId } = await params
  const { searchParams } = new URL(request.url)

  // Verify client exists
  const client = await prisma.enterpriseClient.findUnique({
    where: { id: clientId },
  })

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

  // Parse filters
  const eventType = searchParams.get('type') as ContainerEventType | undefined
  const serverId = searchParams.get('serverId') || undefined
  const limit = parseInt(searchParams.get('limit') || '50', 10)
  const offset = parseInt(searchParams.get('offset') || '0', 10)

  try {
    const result = await containerHealthService.getUnacknowledgedEvents(clientId, {
      eventType,
      serverId,
      limit: Math.min(limit, 200),
      offset,
    })

    return NextResponse.json({
      events: result.events,
      total: result.total,
      pagination: {
        limit,
        offset,
        hasMore: offset + result.events.length < result.total,
      },
    })
  } catch (error) {
    console.error('Failed to get container events:', error)
    return NextResponse.json(
      { error: 'Failed to get container events' },
      { status: 500 }
    )
  }
}

// POST /api/v1/admin/enterprise-clients/[id]/container-events
// Acknowledge container events
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId } = await params

  // Verify client exists
  const client = await prisma.enterpriseClient.findUnique({
    where: { id: clientId },
  })

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

  try {
    const body = await request.json()
    const { eventIds } = body as { eventIds: string[] }

    if (!eventIds || !Array.isArray(eventIds) || eventIds.length === 0) {
      return NextResponse.json(
        { error: 'eventIds array is required' },
        { status: 400 }
      )
    }

    // Verify events belong to this client
    const events = await prisma.containerEvent.findMany({
      where: {
        id: { in: eventIds },
        server: { clientId },
      },
    })

    if (events.length !== eventIds.length) {
      return NextResponse.json(
        { error: 'Some events not found or do not belong to this client' },
        { status: 400 }
      )
    }

    const userId = session.user.email || 'unknown'
    const acknowledgedCount = await containerHealthService.acknowledgeEvents(eventIds, userId)

    return NextResponse.json({
      success: true,
      acknowledged: acknowledgedCount,
    })
  } catch (error) {
    console.error('Failed to acknowledge container events:', error)
    return NextResponse.json(
      { error: 'Failed to acknowledge container events' },
      { status: 500 }
    )
  }
}
