const { connect, close } = require('../src/utils/database');
// We need to import the systems model to register it with mongoose
/* eslint-disable-next-line no-unused-vars */
const System = require('../src/services/system/model');
const { schoolModel: School, yearModel: Year } = require('../src/services/school/model');
const { schoolUsesLdap } = require('../src/services/school/maintenance');
const { info } = require('../src/logger');

module.exports = {
	up: async function up() {
		await connect();

		info('Fetching next school year...');
		const nextYear = await Year.findOne({ name: '2019/20' }).lean().exec();
		info('=>', nextYear);

		info('Fetching schools...');
		const schools = await School.find({})
			.select(['name'])
			.populate(['systems'])
			.lean()
			.exec();
		info(`Got ${schools.length} schools.`);

		for (const school of schools) {
			info(`Migrating ${school.name} (${school._id})...`);
			if (schoolUsesLdap(school)) {
				info('School uses LDAP');
				// schools with active LDAP systems are set into maintenance mode effective immediately
				const result = await School.updateOne({ _id: school._id }, { inMaintenanceSince: Date.now() }).exec();
				info(result);
			} else {
				info('School does not use LDAP');
				// all other schools are migrated to the next year directly
				const result = await School.updateOne({ _id: school._id }, { currentYear: nextYear._id }).exec();
				info(result);
			}
		}

		info('Done.');
		await close();
	},

	down: function down() {
		// not implemented
	},
};

@@ -400,16 +400,25 @@
 t %7B info
+, warning
  %7D = req
@@ -735,16 +735,55 @@
 (%5B'name'
+, 'inMaintenance', 'inMaintenanceSince'
 %5D)%0A%09%09%09.p
@@ -812,16 +812,34 @@
 %09%09.lean(
+%7B virtuals: true %7D
 )%0A%09%09%09.ex
@@ -893,95 +893,322 @@
 %0A%0A%09%09
-for (const school of schools) %7B%0A%09%09%09info(%60Migrating $%7Bschool.name%7D ($%7Bschool._id%7D)...%60);
+const today = Date.now();%0A%09%09info('Maintenance mode for LDAP schools will be effective', today);%0A%0A%09%09for (const school of schools) %7B%0A%09%09%09info(%60Migrating $%7Bschool.name%7D ($%7Bschool._id%7D)...%60);%0A%09%09%09if (school.inMaintenance) %7B%0A%09%09%09%09warning(%60School is already in maintenance mode (since $%7Bschool.inMaintenanceSince%7D)!%60);%0A%09%09%09%7D
 %0A%09%09%09
@@ -1444,26 +1444,21 @@
 eSince: 
-Date.now()
+today
  %7D).exec

Address comments