export const dynamic = 'force-dynamic'
export const runtime = 'nodejs'

import { NextResponse } from 'next/server'
import { isBearerAuthorized, unauthorized, internalHeaders } from '@/lib/voice-tools'

export async function GET(req: Request) {
  if (!isBearerAuthorized(req)) return unauthorized()

  const baseUrl = `http://localhost:${process.env.PORT || '3000'}`
  const r = await fetch(`${baseUrl}/api/ha`, {
    cache: 'no-store',
    headers: internalHeaders(),
  }).catch(() => null)

  if (!r || !r.ok) {
    return NextResponse.json({ error: 'ha_unavailable' }, { status: 502 })
  }

  const data = await r.json()
  const sensors = data.sensors || {}
  const states = data.states || {}
  const purifier = states['fan.air_purifier'] || {}
  const purifierAttrs = purifier.attributes || {}

  return NextResponse.json({
    temperature: sensors.temperature ?? null,
    humidity: sensors.humidity ?? null,
    pm25: sensors.pm25 ?? null,
    air_purifier: {
      state: purifier.state || 'unknown',
      preset_mode: purifierAttrs.preset_mode || null,
      available_modes: purifierAttrs.preset_modes || ['Auto', 'Night', 'High'],
    },
  })
}

export async function POST(req: Request) {
  if (!isBearerAuthorized(req)) return unauthorized()

  const body = await req.json()
  const baseUrl = `http://localhost:${process.env.PORT || '3000'}`

  const r = await fetch(`${baseUrl}/api/ha`, {
    method: 'POST',
    cache: 'no-store',
    headers: { ...internalHeaders(), 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  }).catch(() => null)

  if (!r || !r.ok) {
    return NextResponse.json({ error: 'ha_unavailable' }, { status: 502 })
  }

  return NextResponse.json(await r.json())
}
