const _ = require('lodash');

const db = require('../../db.js');

module.exports = async () => {
	const stops = await db.query(`
		SELECT
			stop_id AS id,
			GROUP_CONCAT(type, ':', destination) AS destinations
		FROM stop_times
		JOIN trips AS trip ON trip.id = trip_id
		JOIN routes AS route ON route.id = route_id
		GROUP BY stop_id
	`);
	
	let query = 'START TRANSACTION;';
	
	// Get the most common destination for all trips serving a stop with coaches having the least priority.
	for (const stop of stops) {
		if (!stop.destinations) continue;
		
		let destinations = stop.destinations.split(',');
		if (destinations.reduce((prev, curr) => prev + Number(curr.startsWith('coach')), 0) !== destinations.length) destinations = destinations.filter((destination) => !destination.startsWith('coach'));
		query += `UPDATE stops SET description = '${_(destinations.map((destination) => destination.split(':')[1])).countBy().entries().maxBy('[1]')[0]}' WHERE id = '${stop.id}';`;
	}
	
	await db.query(query + 'COMMIT;');
};

@@ -142,17 +142,28 @@
 stop
-_id AS id
+.id,%0A%09%09    stop.name
 ,%0A%09%09
@@ -176,16 +176,22 @@
 _CONCAT(
+route.
 type, ':
@@ -237,14 +237,64 @@
 stop
-_times
+s AS stop%0A%09%09JOIN stop_times AS time ON stop_id = stop.id
 %0A%09%09J
@@ -671,16 +671,17 @@
 ;%0A%09%09if (
+!
 destinat
@@ -689,98 +689,63 @@
 ons.
-reduce((prev, curr) =%3E prev + Number(curr.startsWith('coach')), 0) !== destinations.length
+every((destination) =%3E destination.startsWith('coach'))
 ) de
@@ -835,53 +835,32 @@
 ;%0A%09%09
-query += %60UPDATE stops SET description = '$%7B_
+const variants = _.chain
 (des
@@ -868,16 +868,17 @@
 inations
+)
 .map((de
@@ -917,17 +917,16 @@
 ':')%5B1%5D)
-)
 .countBy
@@ -932,32 +932,199 @@
 y().
-entries
+map((value, key) =%3E %5B key, value %5D).sortBy('%5B1%5D').reverse
 ().ma
-xBy('%5B1%5D')%5B0
+p('%5B0%5D').value();%0A%09%09query += %60UPDATE stops SET description = '$%7Bvariants%5BNumber(variants.length %3E 1 && stop.name === variants%5B0%5D)
 %5D%7D' 

Fix matching stop name and destination (api)