import { NextResponse, NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { getToken } from 'next-auth/jwt'

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    const authHeader = req.headers.get('authorization') || req.headers.get('Authorization')
    const bearer = authHeader && authHeader.toLowerCase().startsWith('bearer ') ? authHeader.slice(7) : undefined
    const secret = process.env.NEXTAUTH_SECRET
    const token = await getToken({ req, secret }).catch(() => null)

    let accessToken = session?.accessToken || bearer || (token as any)?.accessToken
    const refreshToken = session?.refreshToken || (token as any)?.refreshToken

    if (!accessToken && refreshToken) {
      try {
        const refreshRes = await fetch(`${process.env.BACKEND_URL}/auth/refresh/`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ refresh: refreshToken }),
        })
        if (refreshRes.ok) {
          const refreshed = await refreshRes.json()
          accessToken = refreshed.access
        }
      } catch {}
    }

    if (!accessToken) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
    }

    const backendUrl = process.env.BACKEND_URL
    if (!backendUrl) {
      return NextResponse.json({ success: false, error: 'BACKEND_URL is not configured' }, { status: 500 })
    }

    const url = new URL(req.url)
    const objectId = url.searchParams.get('objectId')

    const objectsRes = await fetch(`${backendUrl}/account/get-objects/`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
      cache: 'no-store',
    })
 
    const alertsRes = await fetch(`${backendUrl}/account/get-alerts/`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
      cache: 'no-store',
    })

    const payloadText = await alertsRes.text()
    let payload: any
    try { payload = JSON.parse(payloadText) } catch { payload = payloadText }

    if (!alertsRes.ok) {
      const err = typeof payload === 'string' ? payload : JSON.stringify(payload)
      return NextResponse.json({ success: false, error: `Backend alerts error: ${err}` }, { status: alertsRes.status })
    }

    const objectsText = await objectsRes.text()
    let objectsPayload: any
    try { objectsPayload = JSON.parse(objectsText) } catch { objectsPayload = [] }

    const titleToIdMap: Record<string, string> = {}
    if (Array.isArray(objectsPayload)) {
      for (const obj of objectsPayload) {
        if (obj && typeof obj.title === 'string' && typeof obj.id === 'number') {
          titleToIdMap[obj.title] = `object_${obj.id}`
        }
      }
    }

    const list: any[] = Array.isArray(payload) ? payload : []
    const filtered = objectId ? list.filter(a => {
      if (a.object && typeof a.object === 'string') {
        const mappedId = titleToIdMap[a.object] || a.object
        return mappedId === objectId
      }
      return true
    }) : list

    const transformed = filtered.map((a) => {
      const severity = String(a?.severity || a?.type || '').toLowerCase()
      const type = severity === 'critical' ? 'critical' : severity === 'warning' ? 'warning' : 'info'
      const priority = severity === 'critical' ? 'high' : severity === 'warning' ? 'medium' : 'low'
      return {
        id: a.id,
        detector_id: a.detector_id, 
        detector_name: a.name || a.detector_name,
        message: a.message,
        type,
        location: a.object,
        priority,
        acknowledged: typeof a.acknowledged === 'boolean' ? a.acknowledged : !!a.resolved,
        timestamp: a.timestamp || a.created_at,
      }
    })

    return NextResponse.json({ success: true, data: transformed })
  } catch (error) {
    console.error('Error fetching alerts data:', error)
    return NextResponse.json(
      {
        success: false,
        error: 'Failed to fetch alerts data',
      },
      { status: 500 }
    )
  }
}