const { Tickets, LinkedTickets, Members } = require('../../models');
const { errorHandler } = require('../../util');
const { formatCase } = require('../../util/formatter');

exports.getTickets = async (req, res, next) => {
	try {
		let tickets = await Tickets.findAll();

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

//TEST SUPERADMIN
exports.createTicket = async (req, res, next) => {
	try {
		const { ticketNo } = req.body;

		const exists = await Tickets.findOne({
			where: {
				ticket_no: ticketNo,
			},
		});

		if (exists) {
			return errorHandler('Ticket already exists', 400);
		}

		const ticket = await Tickets.create({ ticket_no: ticketNo });

		return res.status(201).json({ success: true, message: 'Ticket Created Successfully', data: ticket });
	} catch (error) {
		next(error);
	}
};

exports.updateTicket = async (req, res, next) => {
	try {
		const { ticketNo } = req.params;
		const updates = req.body;

		let ticket = await Tickets.findOne({
			where: { ticket_no: ticketNo },
		});

		if (!ticket) {
			return errorHandler('Ticket not found', 404);
		}

		await ticket.update(updates);

		return res.status(200).json({
			success: true,
			message: 'Ticket updated successfully',
			data: formatCase(ticket),
		});
	} catch (error) {
		next(error);
	}
};
//TEST SUPERADMIN
exports.getTicket = async (req, res, next) => {
	try {
		const { ticketNo } = req.params;

		let ticket = await Tickets.findOne({
			where: {
				ticket_no: ticketNo,
			},
			include: [
				{
					model: LinkedTickets,
					as: 'linked',
					attributes: ['member_id'],
					include: [
						{
							model: Members,
							as: 'member',
							attributes: ['id', 'first_name', 'middle_name', 'last_name'],
						},
					],
				},
			],
		});

		if (!ticket) {
			return errorHandler('Ticket not found', 404);
		}

		if (ticket.is_used) {
			return errorHandler('Ticket already used', 400);
		}

		ticket = ticket.get({ plain: true });

		ticket.member = ticket?.linked?.member ?? null;
		delete ticket.linked;

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