import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'

export async function POST(req: NextRequest): Promise<NextResponse> {
  try {
    const payload = await getPayload({ config })
    const { user } = await payload.auth({ headers: req.headers })

    if (!user || !(user as { isSuperAdmin?: boolean }).isSuperAdmin) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await req.json()
    const { alertId } = body

    if (!alertId || (typeof alertId !== 'string' && typeof alertId !== 'number')) {
      return NextResponse.json(
        { error: 'alertId must be a string or number' },
        { status: 400 },
      )
    }

    const updated = await payload.update({
      collection: 'monitoring-alert-history',
      id: alertId,
      data: {
        acknowledgedBy: user.id,
        resolvedAt: new Date().toISOString(),
      },
    })

    return NextResponse.json({ data: updated })
  } catch (error: unknown) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}

export const dynamic = 'force-dynamic'
