const {
	Events,
	Activities,
	Restaurants,
	Products,
	ProductImages,
	RestaurantImages,
	ActivityImages,
	sequelize,
} = require('../../models');
const { formatImage } = require('../../util/formatter');

exports.homePage = async (req, res, next) => {
	try {
		let events = await Events.findAll({
			order: [['createdAt', 'DESC']],
			limit: 3,
		});

		events = events.map((item) => {
			const event = item.get({ plain: true });
			event.image = formatImage(event.image, 'event-uploads');
			return event;
		});

		let activities = await Activities.findAll({
			attributes: ['id', 'title', 'location', 'createdAt'],
			include: [{ model: ActivityImages, as: 'images', attributes: ['image'] }],
			order: [['createdAt', 'DESC']],
			limit: 3,
		});

		activities = activities.map((item) => {
			const activity = item.get({ plain: true });
			activity.images = activity.images.map((image) => formatImage(image.image, 'activity-uploads'));
			return activity;
		});

		let restaurants = await Restaurants.findAll({
			attributes: [
				'id',
				'name',
				'price',
				'location',
				[
					sequelize.literal(`(
						SELECT AVG(rating)
						FROM restaurant_reviews
						WHERE restaurant_reviews.restaurant_id = Restaurants.id
					)`),
					'averageRating',
				],
				'createdAt',
			],
			include: [{ model: RestaurantImages, as: 'images', attributes: ['image'] }],
			order: [['createdAt', 'DESC']],
			limit: 3,
		});

		restaurants = restaurants.map((item) => {
			const restaurant = item.get({ plain: true });
			restaurant.images = restaurant.images.map((image) => formatImage(image.image, 'restaurant-uploads'));
			return restaurant;
		});

		let products = await Products.findAll({
			attributes: [
				'id',
				'name',
				'price',
				[
					sequelize.literal(`(
						SELECT SUM(stock)
						FROM product_details
						WHERE product_details.product_id = Products.id
					)`),
					'totalStock',
				],
				'createdAt',
			],
			include: [{ model: ProductImages, as: 'images', attributes: ['image', 'category'] }],
			order: [['createdAt', 'DESC']],
			limit: 4,
		});

		products = products.map((item) => {
			const product = item.get({ plain: true });
			product.images = product.images.map((image) => ({
				...image,
				image: formatImage(image.image, 'product-uploads'),
			}));

			return product;
		});

		return res.status(200).json({
			success: true,
			message: 'Home page data fetched successfully',
			data: {
				events,
				activities,
				restaurants,
				products,
			},
		});
	} catch (error) {
		next(error);
	}
};
