import { sql } from "@/lib/db"
import { type NextRequest, NextResponse } from "next/server"
import bcrypt from "bcryptjs"

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

    if (!token || !password) {
      return NextResponse.json({ error: "Token et mot de passe requis" }, { status: 400 })
    }

    if (password.length < 8) {
      return NextResponse.json({ error: "Le mot de passe doit contenir au moins 8 caractères" }, { status: 400 })
    }

    // Find valid reset token
    const sessions = await sql`
      SELECT user_id FROM user_sessions 
      WHERE token = ${token} 
      AND device_info = 'password_reset'
      AND expires_at > NOW()
    `

    if (sessions.length === 0) {
      return NextResponse.json({ error: "Token invalide ou expiré" }, { status: 400 })
    }

    const userId = sessions[0].user_id

    // Hash new password
    const passwordHash = await bcrypt.hash(password, 10)

    // Update user password
    await sql`
      UPDATE users 
      SET password_hash = ${passwordHash}, updated_at = CURRENT_TIMESTAMP
      WHERE id = ${userId}
    `

    // Delete reset token
    await sql`
      DELETE FROM user_sessions 
      WHERE token = ${token} AND device_info = 'password_reset'
    `

    return NextResponse.json({
      success: true,
      message: "Mot de passe réinitialisé avec succès",
    })
  } catch (error) {
    console.error("Reset password error:", error)
    return NextResponse.json({ error: "Erreur lors de la réinitialisation" }, { status: 500 })
  }
}
