import { NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import * as statusColors from '@/lib/statusColors'

export async function GET() {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.accessToken) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
    }

    const backendUrl = process.env.BACKEND_URL

    const [detectorsRes, objectsRes] = await Promise.all([
      fetch(`${backendUrl}/account/get-detectors/`, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${session.accessToken}`,
        },
        cache: 'no-store',
      }),
      fetch(`${backendUrl}/account/get-objects/`, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${session.accessToken}`,
        },
        cache: 'no-store',
      }),
    ])

    if (!detectorsRes.ok) {
      const err = await detectorsRes.text()
      return NextResponse.json({ success: false, error: `Backend detectors error: ${err}` }, { status: detectorsRes.status })
    }
    if (!objectsRes.ok) {
      const err = await objectsRes.text()
      return NextResponse.json({ success: false, error: `Backend objects error: ${err}` }, { status: objectsRes.status })
    }

    const detectorsPayload = await detectorsRes.json()
    const objectsPayload = await objectsRes.json()
 
    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 statusToColor: Record<string, string> = {
      critical: statusColors.STATUS_COLOR_CRITICAL,
      warning: statusColors.STATUS_COLOR_WARNING,
      normal: statusColors.STATUS_COLOR_NORMAL,
    }

    const transformedDetectors: Record<string, any> = {}
    const detectorsObj = detectorsPayload?.detectors ?? {}
    for (const [key, sensor] of Object.entries<any>(detectorsObj)) {
      const color = statusToColor[sensor.status] ?? statusColors.STATUS_COLOR_NORMAL
      const objectId = titleToIdMap[sensor.object] || sensor.object
      transformedDetectors[key] = {
        ...sensor,
        status: color,
        object: objectId,
        checked: sensor.checked ?? false,
        location: sensor.zone ?? '',
        serial_number: sensor.serial_number ?? sensor.name ?? '',
        detector_type: sensor.detector_type ?? '',
        notifications: Array.isArray(sensor.notifications) ? sensor.notifications.map((n: any) => {
          const severity = String(n?.severity || n?.type || '').toLowerCase()
          const type = severity === 'critical' ? 'critical' : severity === 'warning' ? 'warning' : 'info'
          const priority = severity === 'critical' ? 'high' : severity === 'warning' ? 'medium' : 'low'
          return {
            id: n.id,
            type,
            message: n.message,
            timestamp: n.timestamp || n.created_at,
            acknowledged: typeof n.acknowledged === 'boolean' ? n.acknowledged : !!n.resolved,
            priority,
          }
        }) : []
      }
    }

    return NextResponse.json({
      success: true,
      data: { detectors: transformedDetectors },
      objectsCount: Array.isArray(objectsPayload) ? objectsPayload.length : 0,
      detectorsCount: Object.keys(transformedDetectors).length,
    })
  } catch (error) {
    console.error('Error fetching detectors data:', error)
    return NextResponse.json(
      {
        success: false,
        error: 'Failed to fetch detectors data',
      },
      { status: 500 }
    )
  }
}
