const { Rides, Members, Drivers, Buses } = require('../../models');
const { formatCase } = require('../../util/formatter');

exports.getRides = async (req, res, next) => {
	try {
		const { memberId } = req;

		let rides = await Rides.findAll({
			where: { member_id: memberId },
			attributes: {
				exclude: ['member_id', 'driver_id', 'bus_id'],
			},
			include: [
				{
					model: Members,
					as: 'member',
					attributes: ['id', 'first_name', 'last_name'],
				},
				{
					model: Drivers,
					as: 'driver',
				},
			],
			order: [['createdAt', 'DESC']],
		});

		rides = rides.map((item) => {
			const ride = item.get({ plain: true });
			ride.member = ride.member ? `${ride.member.first_name} ${ride.member.last_name}` : null;
			ride.driver = ride?.driver ? ride?.driver?.driver_name : null;
			ride.busNumber = ride.bus ? ride.bus.bus_number : null;

			delete ride.bus;
			return ride;
		});

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