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

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

    if (!nationalId) {
      return NextResponse.json({ error: "Missing national id." }, { status: 400 })
    }

    const users = (await safeQuery(
      "SELECT national_id, name, is_admin, role, field, department, team, in_shelter, last_updated, must_change_password FROM users WHERE national_id = ?",
      [nationalId],
    )) as any[]

    if (users.length === 0) {
      return NextResponse.json({ error: "User not found." }, { status: 404 })
    }

    return NextResponse.json({ user: users[0] })
  } catch (error) {
    console.error("User fetch error:", error)
    return NextResponse.json({ error: "Failed to load user." }, { status: 500 })
  }
}
