import { getSession } from '@/lib/session'
import { changePassword } from '@/lib/change-password'

export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  let b: Record<string, string> = {}
  try {
    b = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }
  const result = await changePassword(
    session,
    String(b.currentPassword ?? ''),
    String(b.newPassword ?? ''),
    String(b.confPassword ?? ''),
    String(b.token ?? ''),
  )
  if (result.success) {
    session.destroy() // logout por seguridad
  }
  return Response.json(result)
}
