const { Op } = require('sequelize');
const { Discounts } = require('../../models');
const { formatTimestamp } = require('../../util');

exports.getDiscounts = async (req, res, next) => {
	const discounts = await Discounts.findAll({
		where: {
			validity_start_date: {
				[Op.lte]: new Date(),
			},
			validity_end_date: {
				[Op.gte]: new Date(),
			},
		},
	});

	const formatted = formatDiscounts(discounts);

	return res.status(200).json({
		status: 'success',
		data: formatted,
	});
};

exports.getDiscountByCode = async (req, res, next) => {
	const { code } = req.params;

	const discount = await Discounts.findOne({
		where: {
			code,
		},
	});

	if (!discount) {
		return res.status(404).json({
			status: 'error',
			message: 'Discount not found',
		});
	}

	const [formatted] = formatDiscounts([discount]);

	return res.status(200).json({
		status: 'success',
		data: formatted,
	});
};

function formatDiscounts(discounts) {
	return discounts.map((discount) => {
		return {
			id: discount.id,
			name: discount.name,
			description: discount.description,
			code: discount.code,
			type: discount.type,
			percentage: discount.percentage,
			numOfPax: discount.num_of_pax,
			amount: discount.amount,
			validityStartDate: formatTimestamp(discount.validity_start_date),
			validityEndDate: formatTimestamp(discount.validity_end_date),
			createdAt: formatTimestamp(discount.createdAt),
			updatedAt: formatTimestamp(discount.updatedAt),
		};
	});
}
