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

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

  const { id: clientId, errorId } = await params

  // Verify error belongs to a server owned by this client
  const error = await prisma.detectedError.findFirst({
    where: {
      id: errorId,
      server: {
        clientId,
      },
    },
    include: {
      server: true,
    },
  })

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

  if (error.acknowledgedAt) {
    return NextResponse.json({ error: 'Error already acknowledged' }, { status: 400 })
  }

  try {
    const userId = session.user.id || 'unknown'
    await acknowledgeError(errorId, userId)
    return NextResponse.json({ success: true })
  } catch (err) {
    console.error('Failed to acknowledge error:', err)
    return NextResponse.json(
      { error: 'Failed to acknowledge error' },
      { status: 500 }
    )
  }
}
