import { NextRequest, NextResponse } from 'next/server'
import bcrypt from 'bcryptjs'
import pool from '@/lib/db'
import { getSessionFromRequest } from '@/lib/session'

export async function POST(req: NextRequest) {
  const sessionUser = await getSessionFromRequest(req)
  if (!sessionUser) return NextResponse.json({ error: 'Não autorizado' }, { status: 401 })

  const { currentPassword, newPassword } = await req.json()
  if (!currentPassword || !newPassword) {
    return NextResponse.json({ error: 'Campos obrigatórios' }, { status: 400 })
  }

  const [rows] = await pool.execute<any[]>(
    'SELECT password_hash FROM portal_users WHERE id = ?',
    [sessionUser.id]
  )
  const user = rows[0]
  const valid = await bcrypt.compare(currentPassword, user.password_hash)
  if (!valid) return NextResponse.json({ error: 'Senha atual incorreta' }, { status: 400 })

  const hash = await bcrypt.hash(newPassword, 12)
  await pool.execute('UPDATE portal_users SET password_hash = ? WHERE id = ?', [hash, sessionUser.id])

  return NextResponse.json({ ok: true })
}
