const { BusSchedules, BusStops } = require('../../models');
const { formatCase, parseJsonSafe } = require('../../util/formatter');

exports.getAllBusSchedules = async (req, res, next) => {
	try {
		const { date } = req.query;

		let whereClause = {};
		if (date) {
			whereClause.date = date;
		} else {
			whereClause.date = new Date().toISOString().split('T')[0];
		}

		let schedules = await BusSchedules.findAll({
			where: whereClause,
		});

		schedules = schedules.map((item) => {
			const schedule = item.get({ plain: true });
			schedule.times = schedule.times ? parseJsonSafe(schedule.times) : [];
			return schedule;
		});

		return res.status(200).json({
			success: true,
			data: formatCase(schedules),
		});
	} catch (error) {
		next(error);
	}
};

exports.getAllBusStops = async (req, res, next) => {
	try {
		const busStops = await BusStops.findAll({
			order: [['name', 'ASC']],
		});

		return res.status(200).json({
			success: true,
			data: formatCase(busStops.map((stop) => stop.get({ plain: true }))),
		});
	} catch (error) {
		next(error);
	}
};
