const { QueryTypes } = require('sequelize');
const { parseJsonSafe } = require('../../helpers/jsonResponseParser');
const { sequelize, HostsRegistrations } = require('../../models');
const { formatTimestamp } = require('../../util');

exports.getHostProfile = async (req, res, next) => {
	try {
		const { hostId } = req.params;

		const [host] = await sequelize.query(
			`SELECT u.id, u.firstname, u.lastname, u.image, u.hosting_date, u.address_city, u.address_country, u.work, u.languages, u.about_me, u.music, u.pets, u.hangouts, u.likes, u.interests, u.verified,
			(SELECT ROUND(AVG(rating),2) as rating FROM host_reviews WHERE host_reviews.host_id = u.id) as averageRating,
			(SELECT COUNT(*) as reviewsCount FROM host_reviews WHERE host_reviews.host_id = u.id) as reviewsCount
			FROM users u WHERE u.id = ?`,
			{
				type: QueryTypes.SELECT,
				replacements: [hostId],
			},
		);

		if (!host) {
			return res.status(404).json({
				success: false,
				message: 'Host not found',
			});
		}

		const listings = await sequelize.query(
			`
		SELECT 
			l.id, l.name, l.description, l.price, l.address_city, l.address_country,
			(SELECT ROUND(AVG(rating),2) FROM listing_reviews lr WHERE lr.listing_id = l.id) as averageRating,
			(SELECT image FROM listing_images li WHERE li.listing_id = l.id LIMIT 1) as image
		FROM 
			listings l 
		WHERE 
			l.is_deleted = false AND l.host_id = ?`,
			{
				type: QueryTypes.SELECT,
				replacements: [hostId],
			},
		);

		const hostReviews = await sequelize.query(
			`
			SELECT
				hr.content,
				hr.createdAt,
				u.id AS userId,
				u.firstName,
				u.lastName,
				u.image
			FROM host_reviews hr
			JOIN users u ON hr.user_id = u.id
			WHERE hr.host_id = ?
			`,
			{
				type: QueryTypes.SELECT,
				replacements: [hostId],
			},
		);

		const data = {
			id: host.id,
			image: host?.image ? `${process.env.BASE_URL}/public/user-uploads/` + host.image : null,
			fullname: host.firstname + ' ' + host.lastname,
			hostingDate: host?.hosting_date ?? null,
			reviewsCount: host.reviewsCount ?? null,
			averageRating: host?.averageRating,
			verified: host.verified,
			aboutMe: host?.about_me ?? null,
			work: host?.work ?? null,
			address: host?.address_city && host?.address_country ? host.address_city + ', ' + host.address_country : null,
			hobbies: {
				music: host?.music,
				pets: host?.pets,
				hangouts: host?.hangouts,
				likes: host?.likes,
				interests: host?.interests ? parseJsonSafe(host.interests) : [],
			},
			languages: host?.languages ? parseJsonSafe(host.languages) : [],
			listings: listings?.map((listing) => {
				return {
					id: listing.id,
					name: listing.name,
					description: listing.description,
					price: listing.price,
					address:
						listing.address_city && listing.address_country
							? listing.address_city + ', ' + listing.address_country
							: null,
					averageRating: listing?.averageRating,
					image: listing?.image ? `${process.env.BASE_URL}/public/host-uploads/` + listing.image : null,
				};
			}),
			reviews: hostReviews?.map((review) => ({
				id: review.id,
				content: review.content,
				createdAt: formatTimestamp(review.createdAt),
				userId: review.userId,
				fullname: review.firstName + ' ' + review.lastName,
				image: review.image ? `${process.env.BASE_URL}/public/user-uploads/` + review.image : null,
			})),
		};

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