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

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

    // Input validation
    if (!nationalId || !password) {
      return NextResponse.json({ error: "נתונים חסרים" }, { status: 400 })
    }

    if (!validateIsraeliID(nationalId)) {
      return NextResponse.json({ error: "מספר תעודת זהות לא תקין" }, { status: 400 })
    }

    // Use parameterized query to prevent SQL injection
    const users = (await safeQuery(
      "SELECT national_id, password, 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: "משתמש לא נמצא" }, { status: 401 })
    }

    const user = users[0]
    const isValidPassword = await verifyPassword(password, user.password)

    if (!isValidPassword) {
      return NextResponse.json({ error: "סיסמה שגויה" }, { status: 401 })
    }

    return NextResponse.json({
      user: {
        national_id: user.national_id,
        name: user.name,
        is_admin: user.is_admin,
        role: user.role,
        field: user.field,
        department: user.department,
        team: user.team,
        in_shelter: user.in_shelter,
        last_updated: user.last_updated,
        must_change_password: user.must_change_password,
      },
    })
  } catch (error) {
    console.error("Login error:", error)
    return NextResponse.json({ error: "שגיאה בשרת" }, { status: 500 })
  }
}
