const { deleteFile } = require('../../helpers');
const { Events } = require('../../models');
const { formatImage, formatCase } = require('../../util/formatter');

exports.createEvent = async (req, res, next) => {
	try {
		const eventData = { ...req.body };

		if (req.files && req.files.eventImg) {
			eventData.image = req.files.eventImg[0].filename;
		}

		const event = await Events.create(formatCase(eventData, 'snake'));
		return res.status(201).json({ success: true, data: event });
	} catch (error) {
		next(error);
	}
};

exports.getAllEvents = async (req, res, next) => {
	try {
		let events = await Events.findAll({
			order: [['createdAt', 'ASC']],
		});

		events = events.map((event) => {
			let item = event.get({ plain: true });
			item.image = item.image ? formatImage(item.image, 'event-uploads') : null;
			return item;
		});

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

exports.getEvent = async (req, res, next) => {
	try {
		let event = await Events.findByPk(req.params.id);
		if (!event) return res.status(404).json({ success: false, message: 'Event not found' });

		event = event.get({ plain: true });
		event.image = event.image ? formatImage(event.image, 'event-uploads') : null;

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

exports.updateEvent = async (req, res, next) => {
	try {
		const event = await Events.findByPk(req.params.id);
		if (!event) return res.status(404).json({ success: false, message: 'Event not found' });

		const eventData = { ...req.body };

		if (req.files && req.files.eventImg) {
			if (event.image) {
				deleteFile(event.image, 'event-uploads');
			}
			eventData.image = req.files.eventImg[0].filename;
		}

		if (eventData.max_participants !== undefined) {
			eventData.spots_left =
				eventData.max_participants - (eventData.current_participants || event.current_participants || 0);
		}

		await event.update(eventData);
		return res.status(200).json({ success: true, data: event });
	} catch (error) {
		next(error);
	}
};

exports.deleteEvent = async (req, res, next) => {
	try {
		const event = await Events.findByPk(req.params.id);
		if (!event) return res.status(404).json({ success: false, message: 'Event not found' });

		if (event.image) {
			deleteFile(event.image, 'event-uploads');
		}

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