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

exports.createBusStop = async (req, res, next) => {
	try {
		const { name, location, longitude, latitude } = req.body;

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

		const busStop = await BusStops.create({
			name,
			location,
			longitude: parseFloat(longitude),
			latitude: parseFloat(latitude),
		});

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

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

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

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

		await busStop.update(updateData);

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

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

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

		await busStop.destroy();

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

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

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