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

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

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

    if (newPassword.length < 6) {
      return NextResponse.json({ error: "הסיסמה החדשה חייבת להכיל לפחות 6 תווים" }, { status: 400 })
    }

    // Get current user data
    const users = (await safeQuery("SELECT password FROM users WHERE national_id = ?", [nationalId])) as any[]

    if (users.length === 0) {
      return NextResponse.json({ error: "משתמש לא נמצא" }, { status: 404 })
    }

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

    if (!isValidCurrentPassword) {
      return NextResponse.json({ error: "הסיסמה הנוכחית שגויה" }, { status: 401 })
    }

    // Hash new password and update
    const hashedNewPassword = await hashPassword(newPassword)

    await safeQuery(
      "UPDATE users SET password = ?, must_change_password = FALSE, password_changed_at = NOW() WHERE national_id = ?",
      [hashedNewPassword, nationalId],
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Change password error:", error)
    return NextResponse.json({ error: "שגיאה בשינוי סיסמה" }, { status: 500 })
  }
}
