const { Tickets } = 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);
	}
};

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);
	}
};
