import { type NextRequest, NextResponse } from "next/server"
import { safeQuery } from "@/lib/database"
import { broadcastUpdate } from "@/lib/websocket"

export async function POST(request: NextRequest) {
  try {
    const { nationalId, status } = await request.json()

    if (!["yes", "no", "no_alarm", "safe_after_exit"].includes(status)) {
      return NextResponse.json({ error: "סטטוס לא תקין" }, { status: 400 })
    }

    await safeQuery("UPDATE users SET in_shelter = ?, last_updated = NOW() WHERE national_id = ?", [status, nationalId])

    // Broadcast the update to all connected admins
    broadcastUpdate({
      type: "status_change",
      user_id: nationalId,
      status: status,
      timestamp: new Date().toISOString(),
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Status update error:", error)
    return NextResponse.json({ error: "שגיאה בעדכון סטטוס" }, { status: 500 })
  }
}
