export const dynamic = 'force-dynamic'; import { NextRequest, NextResponse } from "next/server"; const HA_URL = process.env.HA_URL || "http://192.168.31.110:8123"; const HA_TOKEN = process.env.HA_TOKEN || ""; // Mock data for demo mode const MOCK_STATES = { "light.living_room": { entity_id: "light.living_room", state: "on", attributes: { brightness: 180, friendly_name: "Свет Гостиная" }, }, "light.bedroom": { entity_id: "light.bedroom", state: "off", attributes: { friendly_name: "Свет Спальня" }, }, "climate.thermostat": { entity_id: "climate.thermostat", state: "heat", attributes: { current_temperature: 21.5, temperature: 22, friendly_name: "Термостат", }, }, "fan.air_purifier": { entity_id: "fan.air_purifier", state: "on", attributes: { preset_mode: "Auto", friendly_name: "Очиститель воздуха", preset_modes: ["Auto", "Night", "High"], }, }, }; export async function GET(req: NextRequest) { if (!HA_TOKEN) { return NextResponse.json({ demo: true, states: MOCK_STATES }); } try { const res = await fetch(`${HA_URL}/api/states`, { headers: { Authorization: `Bearer ${HA_TOKEN}`, "Content-Type": "application/json", }, next: { revalidate: 0 }, }); if (!res.ok) throw new Error(`HA responded ${res.status}`); const states = await res.json(); const relevant = [ "light.living_room", "light.bedroom", "climate.thermostat", "fan.air_purifier", ]; const filtered: Record = {}; for (const s of states) { if (relevant.includes(s.entity_id)) { filtered[s.entity_id] = s; } } return NextResponse.json({ demo: false, states: filtered }); } catch (e) { return NextResponse.json({ demo: true, states: MOCK_STATES }); } } export async function POST(req: NextRequest) { const { domain, service, entity_id, ...serviceData } = await req.json(); if (!HA_TOKEN) { return NextResponse.json({ success: true, demo: true }); } try { const res = await fetch(`${HA_URL}/api/services/${domain}/${service}`, { method: "POST", headers: { Authorization: `Bearer ${HA_TOKEN}`, "Content-Type": "application/json", }, body: JSON.stringify({ entity_id, ...serviceData }), }); if (!res.ok) throw new Error(`HA responded ${res.status}`); return NextResponse.json({ success: true }); } catch (e) { return NextResponse.json({ success: false, error: String(e) }, { status: 500 }); } }