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

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: '#b3261e',
      warning: '#fd7c22',
      normal: '#00ff00',
    }

    const transformedDetectors: Record<string, any> = {}
    const detectorsObj = detectorsPayload?.detectors ?? {}
    for (const [key, sensor] of Object.entries<any>(detectorsObj)) {
      const color = statusToColor[sensor.status] ?? '#00ff00'
      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 ?? '',
      }
    }

    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 }
    )
  }
}