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

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

    if (!hostId) {
      return res.status(400).json({
        success: false,
        message: 'Host ID is required',
      });
    }

    const [host] = await sequelize.query(
      `
			SELECT 
				u.id, 
				u.firstname, 
				u.lastname, 
				u.image, 
				u.createdAt, 
				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,
				u.languages,
				(SELECT ROUND(AVG(rating), 2) FROM host_reviews WHERE host_reviews.host_id = u.id) AS averageRating,
				(SELECT COUNT(*) 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 data = {
      id: host.id,
      image: host.image ? `${process.env.BASE_URL}/public/user-uploads/` + host.image : null,
      fullname: host.firstname + ' ' + host.lastname,
      averageRating: host.averageRating,
      reviewsCount: host.reviewsCount ?? null,
      work: host.work,
      address:
        host?.address_city && host?.address_country
          ? host.address_city + ', ' + host.address_country
          : null,
      createdAt: formatMonthYear(host.createdAt),
      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) : null,
      verified: host.verified,
    };

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