The CJEU said that immigration related detention is justified only in order to prepare the return or carry out the removal process and if the application of less coercive measures would not be sufficient. Only the judicial authority should deal with the decisions concerning the detention of a third-country national (for example an extension) and it should do so following a thorough assessment of all relevant facts and circumstances in the individual case.
Source: official link