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

exports.getAllEvents = async (req, res, next) => {
	try {
		const { status, sortByDate } = req.query;
		const now = new Date();
		let where = {};

		if (status === 'upcoming') {
			where.start_date = { [Op.gt]: now };
			where.status = { [Op.ne]: 'cancelled' };
		} else if (status === 'done') {
			where.end_date = { [Op.lt]: now };
			where.status = { [Op.ne]: 'cancelled' };
		} else if (status === 'cancelled') {
			where.status = 'cancelled';
		} else if (status === 'ongoing') {
			where.start_date = { [Op.lte]: now };
			where.end_date = { [Op.gte]: now };
			where.status = { [Op.ne]: 'cancelled' };
		} else if (status) {
			where.status = status;
		}

		let order = [['createdAt', 'DESC']];
		if (sortByDate) {
			const direction = sortByDate.toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
			order = [['start_date', direction]];
		}

		let events = await Events.findAll({
			where,
			order,
		});

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

			let registration_available = false;
			if (item.status !== 'cancelled') {
				const now = new Date();
				const startDateTime = new Date(`${item.start_date}T${item.start_time || '00:00:00'}`);
				const endDateTime = new Date(`${item.end_date}T${item.end_time || '23:59:59'}`);

				if (now > endDateTime) {
					item.status = 'done';
				} else if (now >= startDateTime && now <= endDateTime) {
					item.status = 'ongoing';
				}

				if (item.registration_start && item.registration_end) {
					const regStart = new Date(item.registration_start);
					const regEnd = new Date(item.registration_end);
					if (now >= regStart && now <= regEnd) {
						registration_available = true;
					}
				}
				item.registration_available = registration_available;
			}

			return item;
		});

		return res.status(200).json({ success: true, data: formatCase(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);
	}
};
