import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import crypto from 'crypto'
import { sendPasswordResetEmail } from '@/lib/email'

export async function POST(req: NextRequest) {
  try {
    const { email } = await req.json()
    if (!email) {
      return NextResponse.json({ error: 'Email wajib diisi' }, { status: 400 })
    }

    const user = await prisma.user.findUnique({ where: { email } })
    if (!user) {
      // Don't leak whether the email exists or not
      return NextResponse.json({ success: true })
    }

    // Generate random token
    const token = crypto.randomBytes(32).toString('hex')
    const tokenExp = new Date(Date.now() + 60 * 60 * 1000) // 1 hour expiry

    // Save to database
    await prisma.user.update({
      where: { id: user.id },
      data: {
        resetToken: token,
        resetTokenExp: tokenExp,
      },
    })

    // Create reset URL
    const baseUrl = process.env.APP_URL || 'http://localhost:3000'
    const resetUrl = `${baseUrl}/auth/reset-password?token=${token}`

    // Send email
    await sendPasswordResetEmail(user.email, {
      name: user.name,
      resetUrl,
    })

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('[FORGOT PASSWORD]', error)
    return NextResponse.json({ error: 'Terjadi kesalahan internal' }, { status: 500 })
  }
}
