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

exports.createTicket = async (req, res, next) => {
	try {
		const ticket = await WorldConTickets.create(req.body);

		if (req.files && req.files.worldConTicketImg) {
			const imagePath = req.files.worldConTicketImg[0].filename;
			await ticket.update({ image: imagePath });
			ticket.image = imagePath;
		}
		return res.status(201).json({ success: true, data: ticket });
	} catch (error) {
		next(error);
	}
};

exports.getAllTickets = async (req, res, next) => {
	try {
		let tickets = await WorldConTickets.findAll({
			order: [['createdAt', 'DESC']],
		});

		tickets = tickets.map((ticket) => {
			let item = ticket.get({ plain: true });
			item.image = item.image ? formatImage(item.image, 'world-con-tickets-uploads') : null;

			return item;
		});

		tickets = formatCase(tickets);

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

exports.getTicket = async (req, res, next) => {
	try {
		const ticket = await WorldConTickets.findByPk(req.params.id);
		if (!ticket) return res.status(404).json({ success: false, message: 'Ticket not found' });
		return res.status(200).json({ success: true, data: ticket });
	} catch (error) {
		next(error);
	}
};

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

		if (req.files && req.files.worldConTicketImg) {
			const oldImage = ticket.image;
			if (oldImage) {
				deleteFile(oldImage, 'world-con-tickets-uploads');
			}

			const imagePath = req.files.worldConTicketImg[0].filename;
			req.body.image = imagePath;
		}

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

exports.deleteTicket = async (req, res, next) => {
	try {
		const ticket = await WorldConTickets.findByPk(req.params.id);
		if (!ticket) return res.status(404).json({ success: false, message: 'Ticket not found' });
		await ticket.destroy();
		return res.status(200).json({ success: true, message: 'Ticket deleted' });
	} catch (error) {
		next(error);
	}
};
