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

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);
  });
};

/////////////////////                V1.1            ///////////////////////////////////////
exports.createHostRegistrationV2 = async (userId, data, files) => {
  try {
    // const { selfieImg } = files || {};

    const hostRegistration = await 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,
      // duration: data.duration,
      // location_type: data.locationType ? JSON.stringify(data.locationType) : null,
      location_description: data.locationDescription,
      hosting_type: data.hostingType,
      fullname: data.fullname,
      listing_name: data.listingName,
      listing_type: data.listingType,
      amenities: data.amenities ? JSON.stringify(data.amenities) : null,
      services: data.services ? JSON.stringify(data.services) : null,
      listing_description: data.description,
      check_in_time: data.checkInTime,
      check_out_time: data.checkOutTime,
      smoking_policy: data.smokingPolicy,
      pets_policy: data.petsPolicy,
      quiet_hours_start: data.quietHoursStart,
      quiet_hours_end: data.quietHoursEnd,
      discount_weekly: data.discountWeekly,
      discount_monthly: data.discountMonthly,
      discount_weekly_percentage: data.discountWeeklyPercentage,
      discount_monthly_percentage: data.discountMonthlyPercentage,
      security_deposit: data.securityDeposit,
      security_deposit_price: data.securityDepositPrice,
      // 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,

      capacity: data.capacity,
      individual_rate: data.individualRate,
      travelers_discounts: data.travelersDiscounts,

      cancellation_policy: data.cancellationPolicy,
      // selfie_image: selfieImg ? selfieImg[0].filename : null,
    });

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

      await HostRegistrationAddOns.bulkCreate(addOnRecords);
    }

    const fileRecords = handleFiles(files, hostRegistration.id);

    if (fileRecords.length > 0) {
      await HostRegistrationFiles.bulkCreate(fileRecords);
    }

    return hostRegistration;
  } catch (error) {
    return Promise.reject(errorHandler('Error creating host registration.', 500));
  }
};

/////////////////////                V1.1            ///////////////////////////////////////
