import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { getDetectedErrors } from '@/lib/services/error-detection-service'
import type { ErrorSeverity } from '@prisma/client'

// GET /api/v1/admin/enterprise-clients/[id]/errors
// List detected errors 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 serverId = searchParams.get('serverId') || undefined
  const severity = searchParams.get('severity') as ErrorSeverity | undefined
  const acknowledgedParam = searchParams.get('acknowledged')
  const acknowledged = acknowledgedParam === 'true' ? true : acknowledgedParam === 'false' ? false : undefined
  const ruleId = searchParams.get('ruleId') || undefined
  const limit = parseInt(searchParams.get('limit') || '100', 10)
  const offset = parseInt(searchParams.get('offset') || '0', 10)

  try {
    const errors = await getDetectedErrors(clientId, {
      serverId,
      severity,
      acknowledged,
      ruleId,
      limit: Math.min(limit, 500), // Cap at 500
      offset,
    })

    return NextResponse.json(errors)
  } catch (error) {
    console.error('Failed to get detected errors:', error)
    return NextResponse.json(
      { error: 'Failed to get detected errors' },
      { status: 500 }
    )
  }
}
