const { BusSchedules, sequelize, RouteSchedules } = require('../../models');
const { errorHandler } = require('../../util');
const { formatCase } = require('../../util/formatter');

exports.createBusSchedule = async (req, res, next) => {
	let transaction = await sequelize.transaction();
	try {
		const route_schedule = await RouteSchedules.findByPk(req.body.route_schedule_id);
		if (!route_schedule) return errorHandler('Route schedule not found', 404);
		const driverRoute = await BusSchedules.create({ ...req.body, route_id: route_schedule.route_id }, { transaction });
		await transaction.commit();
		return res.status(201).json({ success: true, data: formatCase(driverRoute.get({ plain: true })) });
	} catch (err) {
		if (transaction) await transaction.rollback();
		next(err);
	}
};

exports.getBusSchedules = async (req, res, next) => {
	try {
		const { page = 1, limit = 20 } = req.query;
		const offset = (parseInt(page) - 1) * parseInt(limit);
		const { count, rows } = await BusSchedules.findAndCountAll({
			order: [['createdAt', 'DESC']],
			limit: parseInt(limit),
			offset,
		});
		return res.status(200).json({
			success: true,
			data: formatCase(rows.map((r) => r.get({ plain: true }))),

			pagination: {
				currentPage: parseInt(page),
				totalPages: Math.ceil(count / parseInt(limit)),
				totalItems: count,
				itemsPerPage: parseInt(limit),
			},
		});
	} catch (err) {
		next(err);
	}
};

exports.getBusSchedule = async (req, res, next) => {
	try {
		const driverRoute = await BusSchedules.findByPk(req.params.id);
		if (!driverRoute) return errorHandler('Driver route not found', 404);
		return res.status(200).json({ success: true, data: formatCase(driverRoute.get({ plain: true })) });
	} catch (err) {
		next(err);
	}
};

exports.updateBusSchedule = async (req, res, next) => {
	let transaction = await sequelize.transaction();
	try {
		const driverRoute = await BusSchedules.findByPk(req.params.id);
		if (!driverRoute) return errorHandler('Driver route not found', 404);
		await driverRoute.update(req.body, { transaction });
		await transaction.commit();
		return res.status(200).json({ success: true, data: formatCase(driverRoute.get({ plain: true })) });
	} catch (err) {
		if (transaction) await transaction.rollback();
		next(err);
	}
};

exports.deleteBusSchedule = async (req, res, next) => {
	let transaction = await sequelize.transaction();
	try {
		const driverRoute = await BusSchedules.findByPk(req.params.id);
		if (!driverRoute) return errorHandler('Driver route not found', 404);
		await driverRoute.destroy({ transaction });
		await transaction.commit();
		return res.status(200).json({ success: true, message: 'Driver route deleted' });
	} catch (err) {
		if (transaction) await transaction.rollback();
		next(err);
	}
};
