const { Buses } = require('../../models');
const { errorHandler } = require('../../util');
const { formatCase } = require('../../util/formatter');

exports.createBus = async (req, res, next) => {
	try {
		const { longitude, latitude, bus_number } = req.body;

		if (!longitude || !latitude) {
			return errorHandler('Longitude and latitude are required', 400);
		}

		const exists = await Buses.findOne({
			where: {
				bus_number,
			},
		});

		if (exists) {
			return errorHandler('Bus with this number already exists', 400);
		}

		const bus = await Buses.create({
			longitude,
			latitude,
			bus_number,
		});

		return res.status(201).json({
			success: true,
			message: 'Bus created successfully',
			data: formatCase(bus.get({ plain: true })),
		});
	} catch (error) {
		next(error);
	}
};

exports.updateBus = async (req, res, next) => {
	try {
		const { longitude, latitude, id } = req.body;

		const bus = await Buses.findByPk(id);
		if (!bus) {
			return errorHandler('Bus not found', 404);
		}

		const updateData = {};
		if (longitude !== undefined) updateData.longitude = parseFloat(longitude);
		if (latitude !== undefined) updateData.latitude = parseFloat(latitude);

		await bus.update(updateData);

		return res.status(200).json({
			success: true,
			message: 'Bus updated successfully',
			data: formatCase(bus.get({ plain: true })),
		});
	} catch (error) {
		next(error);
	}
};

exports.deleteBus = async (req, res, next) => {
	try {
		const { id } = req.params;

		const bus = await Buses.findByPk(id);
		if (!bus) {
			return errorHandler('Bus not found', 404);
		}

		await bus.destroy();

		return res.status(200).json({
			success: true,
			message: 'Bus deleted successfully',
		});
	} catch (error) {
		next(error);
	}
};
