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

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

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

exports.getLinkedTickets = async (req, res, next) => {
	try {
		let tickets = await LinkedTickets.findAll({
			where: {
				member_id: req.memberId,
			},
			include: [
				{
					model: Tickets,
					as: 'ticket',
					include: [
						{
							model: WorldConTickets,
							as: 'worldConTicket',
							attributes: ['id', 'title', 'location', 'start_date', 'end_date'],
						},
					],
				},
				{
					model: Members,
					as: 'member',
					attributes: ['id', 'first_name', 'last_name'],
				},
			],
		});

		tickets = tickets.map((item) => {
			const ticket = item.get({ plain: true });

			return {
				id: ticket.id,
				ticketNo: ticket.ticket_no,
				title: ticket.ticket.worldConTicket.title,
				location: ticket.ticket.worldConTicket.location,
				startDate: ticket.ticket.worldConTicket.start_date,
				endDate: ticket.ticket.worldConTicket.end_date,
				member: `${ticket.member.first_name} ${ticket.member.last_name}`,
				isUsed: ticket.ticket.is_used,
				isLinked: true,
			};
		});

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

exports.linkTicket = async (req, res, next) => {
	try {
		const { ticketNo } = req.body;
		const { memberId } = req;

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

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

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

		if (exists) {
			if (exists.member_id === memberId) {
				return errorHandler('Ticket already linked', 400);
			}

			return errorHandler('Ticket already linked to another member', 400);
		}

		const linkedTicket = await LinkedTickets.create({ member_id: memberId, ticket_no: ticketNo });

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