const { EventRegistrations, Members, Events } = require('../../models');
const { formatImage } = require('../../util/formatter');

exports.getAllEventRegistrations = async (req, res, next) => {
	try {
		const { event_id, status } = req.query;

		const whereClause = {};
		if (event_id) whereClause.event_id = event_id;
		if (status) whereClause.status = status;

		let registrations = await EventRegistrations.findAll({
			where: whereClause,
			include: [
				{
					model: Members,
					as: 'member',
					attributes: ['id', 'first_name', 'last_name', 'email_address', 'phone_number'],
				},
				{
					model: Events,
					as: 'event',
					attributes: ['id', 'title', 'location', 'start_date', 'end_date', 'image'],
				},
			],
			order: [['createdAt', 'DESC']],
		});

		registrations = registrations.map((registration) => {
			let item = registration.get({ plain: true });
			if (item.event && item.event.image) {
				item.event.image = formatImage(item.event.image, 'event-uploads');
			}
			return item;
		});

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

exports.getEventRegistration = async (req, res, next) => {
	try {
		let registration = await EventRegistrations.findByPk(req.params.id, {
			include: [
				{
					model: Members,
					as: 'member',
					attributes: ['id', 'first_name', 'last_name', 'email_address', 'phone_number'],
				},
				{
					model: Events,
					as: 'event',
					attributes: ['id', 'title', 'location', 'start_date', 'end_date', 'image'],
				},
			],
		});

		if (!registration) {
			return res.status(404).json({ success: false, message: 'Registration not found' });
		}

		registration = registration.get({ plain: true });
		if (registration.event && registration.event.image) {
			registration.event.image = formatImage(registration.event.image, 'event-uploads');
		}

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

// exports.updateRegistrationStatus = async (req, res, next) => {
// 	try {
// 		const { status } = req.body;

// 		const registration = await EventRegistrations.findByPk(req.params.id);
// 		if (!registration) {
// 			return res.status(404).json({ success: false, message: 'Registration not found' });
// 		}

// 		await registration.update({ status });
// 		return res.status(200).json({ success: true, data: registration, message: 'Registration status updated' });
// 	} catch (error) {
// 		next(error);
// 	}
// };

// exports.deleteEventRegistration = async (req, res, next) => {
// 	try {
// 		const registration = await EventRegistrations.findByPk(req.params.id);
// 		if (!registration) {
// 			return res.status(404).json({ success: false, message: 'Registration not found' });
// 		}

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