const {
	HostsRegistrations,
	Users,
	HostRegistrationFiles,
	HostRegistrationAddOns,
	ListingAddOns,
} = require('../models');
const { errorHandler, handleFiles } = require('../util');

exports.checkUserStatus = (userId) => {
	return Users.findOne({ where: { id: userId } }).then((user) => {
		if (!user) {
			return Promise.reject(errorHandler('User not found.', 404));
		}

		// return HostsRegistrations.findOne({
		// 	where: { user_id: userId, status: 'Pending' },
		// }).then((existingUser) => {
		// 	if (existingUser) {
		// 		return Promise.reject(errorHandler('User has a pending application.', 400));
		// 	}
		// 	return user;
		// });
	});
};

exports.createHostRegistration = (userId, data, files) => {
	const { selfieImg } = files || {};

	return HostsRegistrations.create({
		user_id: userId,
		city_to_hosts: data.cityToHost,
		languages: data.languages ? JSON.stringify(data.languages) : null,
		is_partner_org: data.isPartnerOrg,
		about_me: data.aboutMe,
		themes: data.themes ? JSON.stringify(data.themes) : null,
		listing_description: data.description,
		duration: data.duration,
		location_type: data.locationType ? JSON.stringify(data.locationType) : null,
		location_description: data.locationDescription,
		hosting_type: data.hostingType,
		address_country: data.addressCountry,
		address_street: data.addressStreet,
		address_apt: data.addressApt,
		address_city: data.addressCity,
		address_state: data.addressState,
		address_zip: data.addressZip,
		location_lat: data.locationLat,
		location_long: data.locationLong,
		amenities: data.amenities ? JSON.stringify(data.amenities) : null,
		services: data.services ? JSON.stringify(data.services) : null,
		listing_name: data.listingName,
		capacity: data.capacity,
		individual_rate: data.individualRate,
		travelers_discounts: data.travelersDiscounts,
		check_in_time: data.checkInTime,
		check_out_time: data.checkOutTime,
		cancellation_policy: data.cancellationPolicy,
		selfie_image: selfieImg ? selfieImg[0].filename : null,
	}).then((newUser) => {
		const fileRecords = handleFiles(files, newUser.id);

		if (data.addOns && data.addOns.length > 0) {
			const addOnRecords = data.addOns.map((addOn) => ({
				host_registration_id: newUser.id,
				add_on_name: addOn.name,
				price: addOn.price || 0.0,
			}));

			return HostRegistrationAddOns.bulkCreate(addOnRecords).then(() => {
				if (fileRecords.length > 0) {
					return HostRegistrationFiles.bulkCreate(fileRecords).then(() => newUser);
				}

				return newUser;
			});
		}

		return newUser;
	});
};

exports.updateUserStatus = (userId) => {
	return Users.update({ has_pending_host_application: true }, { where: { id: userId } });
};

exports.findHostRegistrationById = (applicationId) => {
	return HostsRegistrations.findByPk(applicationId, {
		include: [
			{
				model: HostRegistrationFiles,
				as: 'files',
				where: { file_type: 'Listing Images' },
				required: false,
			},
		],
	});
};

exports.approveHostRegistration = (applicationId) => {
	return HostsRegistrations.update({ status: 'Approved' }, { where: { id: applicationId } });
};

exports.createListingAddOns = (listingId, hostRegistrationId) => {
	return HostRegistrationAddOns.findAll({
		where: { host_registration_id: hostRegistrationId },
	}).then((addOns) => {
		const listingAddOnsPromises = addOns.map((addOn) =>
			ListingAddOns.create({
				listing_id: listingId,
				add_on_name: addOn.add_on_name,
				price: addOn.price,
			}),
		);
		return Promise.all(listingAddOnsPromises);
	});
};
