import { sql } from "@/lib/db"
import { type NextRequest, NextResponse } from "next/server"
import { v4 as uuidv4 } from "uuid"

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

    if (!email) {
      return NextResponse.json({ error: "Email requis" }, { status: 400 })
    }

    // Find user by email
    const users = await sql`
      SELECT id, email, name FROM users WHERE email = ${email.toLowerCase()}
    `

    if (users.length === 0) {
      // Don't reveal if email exists for security
      return NextResponse.json({
        success: true,
        message: "Si cet email existe, un lien de réinitialisation a été envoyé",
      })
    }

    const user = users[0]

    // Generate reset token
    const resetToken = uuidv4()
    const expiresAt = new Date(Date.now() + 60 * 60 * 1000) // 1 hour

    // Store reset token (in production, store hash of token)
    await sql`
      INSERT INTO user_sessions (user_id, token, expires_at, device_info)
      VALUES (${user.id}, ${resetToken}, ${expiresAt}, 'password_reset')
    `

    // TODO: Send email using email service
    // const resetLink = `${process.env.NEXT_PUBLIC_APP_URL}/reset-password?token=${resetToken}`
    // await sendPasswordResetEmail(email, resetLink)

    return NextResponse.json({
      success: true,
      message: "Si cet email existe, un lien de réinitialisation a été envoyé",
      // Dev only - remove in production
      resetToken: process.env.NODE_ENV === "development" ? resetToken : undefined,
    })
  } catch (error) {
    console.error("Forgot password error:", error)
    return NextResponse.json({ error: "Erreur lors de l'envoi du lien" }, { status: 500 })
  }
}
