import { Injectable, HttpException, HttpStatus, Res } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Not, IsNull } from 'typeorm';
import { classToPlain } from 'class-transformer';
import { responseMessages } from '../../messages/response-messages';
import { emailMessages } from '../../messages/email-messages';
import { AuthRepository } from './repositories/auth.repository';
import * as bcrypt from 'bcryptjs';
import { HttpService } from '@nestjs/axios';
import { Constants } from '../../common/constants';
import { JwtService } from '@nestjs/jwt';
const moment = require('moment-timezone');
// DTO Files
import { UserLoginDto } from "./dtos/user-login.dto";
import { UserSocialLoginDto } from './dtos/user-social-login.dto';
import { SendMailService } from '../../common/config/send-mail.service';
import { RecaptchaService } from '../../common/config/recaptcha.service';

// Entities Files
import { UserRoles, Users } from "../../entities/users.entity";

import { title } from 'process';
import { UserRegisterDto } from './dtos/user-register.dto';
import { VerifyOtpDto } from './dtos/verify-otp.dto';
import { ForgotPasswordDto } from './dtos/forgot-password.dto';
import { ResetPasswordDto } from './dtos/reset-password.dto';
import { SocialLoginDto } from './dtos/social-login.dto';
import { UsersServices } from 'src/common/services/users/users.service';
import slugify from 'slugify';
import { CampaignInfluencer, InfluencerStatus } from 'src/entities/campaign_influencer.entity';
import { NotificationService } from 'src/common/services/notification/notification.service';
import { notificationMessages } from 'src/messages/notifications-messages';
import { notificationSettings } from 'src/messages/notification-settings';
import { RedirectType } from 'src/entities/notifications.entity';
import { GuestUserProfileAccess } from 'src/entities/guest_user_profile_access.entity';
import { uploadFileToS3 } from 'src/common/config/upload-s3-file-using-link';
import { ErrorLogService } from 'src/common/services/error-logs/error-log.service';
import { CommonService } from '../common/common.services';
import { WhatsAppServices } from 'src/common/services/whatsapp/whatsapp.service';
import { VerifyWhatsAppDto } from './dtos/veridy-whatsapp.dto';
import { NotificationPreferencesService } from '../notification-preferences/notification-preferences.service';
import { Countries } from 'src/entities/countries.entity';
const { slugify: translitSlug } = require("transliteration");

@Injectable()
export class AuthService {

    constructor(
        private authRepository: AuthRepository,
        private httpService: HttpService,
        private jwtService: JwtService,
        private sendMailService: SendMailService,
        private recaptchaService: RecaptchaService,
        private userService: UsersServices,
        private errorLogService: ErrorLogService,
        private whatsappService: WhatsAppServices,
        private notificationPreferencesService: NotificationPreferencesService,
        @InjectRepository(Users)
        private Users: Repository<Users>,

        @InjectRepository(CampaignInfluencer)
        private CampaignInfluencer: Repository<CampaignInfluencer>,

        @InjectRepository(GuestUserProfileAccess)
        private GuestUserProfileAccess: Repository<GuestUserProfileAccess>,

        @InjectRepository(Countries)
        private Countries: Repository<Countries>,


    ) { }

    async userRegister(request: UserRegisterDto) {
        const existEmail = await this.Users.createQueryBuilder('user')
            .where('LOWER(user.email) = LOWER(:email)', { email: request.email })
            .andWhere('user.is_imported_by_admin = false')
            .getOne();
        if (existEmail) {
            throw new HttpException(responseMessages.en.user.email_already_exists, HttpStatus.NOT_FOUND);
        }

        if (request.phone_number) {
            const phoneNumberExists = await this.Users.createQueryBuilder('user')
                .where('user.phone_number = :phone_number', { phone_number: request.phone_number })
                .andWhere('user.is_whatsapp_verified = true')
                .getOne();
            if (phoneNumberExists) {
                throw new HttpException(responseMessages.en.user.phone_number_already_exists, HttpStatus.NOT_FOUND);
            }
        }

        // if (request?.display_name) {
        //     const existDisplayName = await this.Users.createQueryBuilder('user')
        //         .where('LOWER(user.display_name) = LOWER(:display_name)', { display_name: request.display_name })
        //         .andWhere('user.is_imported_by_admin = false')
        //         .getOne();
        //     if (existDisplayName) {
        //         throw new HttpException(responseMessages.en.user.display_name_already_exists, HttpStatus.NOT_FOUND);
        //     }
        // }


        // CHECK WITH EMAIL: LINK ACCOUNT WITH IMPORTED ACCOUNT WHICH IS IMPORTED BY ADMIN
        const linkEmail = await this.Users.findOne({ where: [{ email: request.email, role: 'influencer', is_imported_by_admin: true }] });
        if (linkEmail) {
            request.id = linkEmail.id;
        }

        const otp = Math.floor(100000 + Math.random() * 900000);
        request['otp'] = otp;
        request['otp_time'] = new Date();
        request['password'] = await bcrypt.hash(request.password, Constants.salt_rounds);
        request['slug'] = await this.generateSlug(request.first_name, request.last_name);
        request['is_imported_by_admin'] = false;
        request['whatsapp_phone_number'] = `${request.country_code}${request.phone_number}`.replace('+', '');
        request['email'] = request.email.toLowerCase();
        if (request.social_id) {
            request['is_verify_otp'] = true;
        }

        const newUser = await this.authRepository.createWithObject(request);

        if (request.social_id) {
            //receiver,description,sender = null,redirect_type = null,redirect_id = null,redirect_slug = null
            const adminMessage = notificationMessages.en.descriptions.new_user_registered.replace(':userName', `${newUser.first_name} ${newUser.last_name}`).replace(":role", request.role);
            const redirect_type = request.role == 'brand' ? RedirectType.BRAND_LIST : RedirectType.INFLUENCER_LIST;
            this.sendNotificationAndEmail(newUser, 'new_user_registered', {
                description: adminMessage,
                sender: newUser,
                redirect_type,
                redirect_id: newUser.id,
                redirect_slug: newUser.slug,
            });

            const { created_at, updated_at, deleted_at, otp, otp_time, password, ...modifiedUser } = newUser;

            const payload = { sub: newUser.id, username: newUser.email };
            return {
                ...modifiedUser,
                access_token: this.jwtService.sign(payload),
                // profile_path : process.env.AWS_PROFILE_FILE_PATH,
            };
        }
        this.sendNotificationAndEmail(newUser, 'verify_otp_email', {
            metadata: { otp: otp.toString() },
        });

        return;
    }


    async sendEmail(receiver, metadata, type) {
        const emailSetting = notificationSettings?.[type];
        if (emailSetting && emailSetting.email === false) {
            return;
        }
        if (!receiver?.email || !emailMessages?.en?.[type]) {
            return;
        }
        const name = `${receiver.first_name} ${receiver.last_name}`;
        const mailSubject = emailMessages.en[type].subject;
        const mailTitle = emailMessages.en[type].title;
        const mailDescription = emailMessages.en[type].description.replace(':otp', metadata?.otp || '');

        this.sendMailService.sendMailObjectWithTemplates(receiver.email, mailSubject, 'common_mail', {
            hello_user_name: emailMessages.en.hello_user_name.replace(':user_name', name),
            main_title: mailTitle,
            descriptions: mailDescription,
            copyright: emailMessages.en.copyright,
            all_rights_reserved: emailMessages.en.all_rights_reserved,
        });
    }

    async sendNotificationAndEmail(
        receiver,
        type,
        options: {
            metadata?: any;
            description?: string;
            sender?: any;
            redirect_type?: RedirectType;
            redirect_id?: string;
            redirect_slug?: string;
        } = {}
    ) {
        const { metadata = {}, description = '', sender = null, redirect_type = null, redirect_id = null, redirect_slug = null } = options;

        const settings = notificationSettings?.[type] || {};

        if (settings.in_app && description) {
            this.authRepository.notification(description, sender, redirect_type, redirect_id, redirect_slug);
        }

        if (settings.email) {
            this.sendEmail(receiver, metadata, type);
        }
    }


    async generateUniqueSlug(name: string) {

    }

    // Function to generate slug
    async generateSlug(firstName, lastName) {

        // Generate initial slug from the name
        let slug = slugify(translitSlug(`${firstName} ${lastName}`), { lower: true, strict: true });

        // Check if the slug exists
        let existing = await this.Users.findOne({ where: { slug }, withDeleted: true });

        // If slug exists, append a 4-character random string
        if (existing) {
            const randomString = Math.random().toString(36).substring(2, 6); // Generate a 4-character random string
            slug = `${slug}-${randomString}`;
        }

        return slug;
    }
    async createAssessToken(id, email) {
        const payload = { sub: id, username: email };
        return await this.jwtService.sign(payload);
    }

    async verifyOtp(request: VerifyOtpDto) {
        const lang = request.language_code || 'en';
        const existUser = await this.Users.createQueryBuilder('user')
            .where('LOWER(user.email) = LOWER(:email)', { email: request.email })
            .getOne();
        if (!existUser) {
            throw new HttpException(responseMessages[lang].user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        if (existUser.otp == request.otp) {
            const currentDate = new Date();
            // const existCurrentDate = new Date(existUser.otp_time);
            // let originalDate = moment.utc(existUser.otp_time).format('YYYY-MM-DD HH:mm:ss');
            // const [existDatePart, existTimePart] = originalDate.split(' ');
            // const formattedDateString = `${existDatePart}T${existTimePart}.00Z`;
            const existDateTime = new Date(existUser.otp_time);
            const differenceInSeconds = Math.floor((currentDate.getTime() - existDateTime.getTime()) / 1000);

            if (differenceInSeconds < 120) {
                if (existUser.role != 'admin') {
                    if (!existUser.is_whatsapp_verified) {
                        const whatsAppRequest = {
                            phone_number: existUser.phone_number,
                            country_code: existUser.country_code,
                        }
                        this.verifyWhatsApp(whatsAppRequest, existUser);
                    }
                    // Enable all notification preferences by default for new users
                    await this.notificationPreferencesService.createDefaultPreferencesForUser(existUser.id);

                    // SEND NOTIFICATION TO ADMIN
                    const adminMessage = notificationMessages.en.descriptions.new_user_registered.replace(':userName', `${existUser.first_name} ${existUser.last_name}`).replace(":role", existUser.role);
                    const redirect_type = existUser.role == 'brand' ? RedirectType.BRAND_LIST : RedirectType.INFLUENCER_LIST;
                    this.sendNotificationAndEmail(existUser, 'new_user_registered', {
                        description: adminMessage,
                        sender: existUser,
                        redirect_type,
                        redirect_id: existUser.id,
                        redirect_slug: existUser.slug,
                    });
                    existUser['is_verify_otp'] = true;
                    existUser['language'] = lang;

                    await this.Users.save(existUser);
                }

                const { created_at, updated_at, deleted_at, otp, otp_time, password, ...modifiedUser } = existUser;

                const payload = { sub: existUser.id, username: existUser.email };
                return {
                    ...modifiedUser,
                    profile_path: process.env.AWS_FILE_PATH + 'images/profile/',
                    campaign_path: process.env.AWS_FILE_PATH + 'files/campaign/',
                    campaign_receipt_path: process.env.AWS_FILE_PATH + 'files/campaign/receipt/',
                    draft_path: process.env.AWS_FILE_PATH + 'files/draft/',
                    dispute_path: process.env.AWS_FILE_PATH + 'files/dispute/',
                    advertisement_path: process.env.AWS_FILE_PATH + 'images/advertisement/',
                    bank_path: process.env.AWS_FILE_PATH + 'images/bank/',
                    access_token: this.jwtService.sign(payload),
                    // profile_path : process.env.AWS_PROFILE_FILE_PATH,
                };
            } else {
                throw new HttpException(responseMessages[lang].user.otp_expired, HttpStatus.BAD_REQUEST);
            }

        } else {
            throw new HttpException(responseMessages[lang].user.otp_invalid, HttpStatus.BAD_REQUEST);
        }

    }

    async userLogin(request: UserLoginDto) {

        const lang = request.language_code || 'en';
        const existsUser = await this.Users.createQueryBuilder('user')
            .where('LOWER(user.email) = LOWER(:email)', { email: request.email })
            .getOne();


        if (!existsUser) {
            throw new HttpException(responseMessages[lang].user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        if (request.recaptcha_token) {
            const tokenverified = await this.recaptchaService.verifyRecaptcha(request.recaptcha_token);

            if (!tokenverified) {
                throw new HttpException(responseMessages[lang].user.recaptcha_invalid, HttpStatus.NOT_FOUND);
            }
        }

        if (!existsUser.is_active) {
            throw new HttpException(responseMessages.en.user.account_inactive, HttpStatus.BAD_REQUEST);
        }

        const comparedPass = await bcrypt.compare(request.password, existsUser.password);

        if (!comparedPass) {
            throw new HttpException(responseMessages[lang].user.password_incorrect, HttpStatus.BAD_REQUEST);
        }

        const payload = { sub: existsUser.id, username: existsUser.email };
        let access_token = await this.jwtService.sign(payload);
        if (existsUser.is_verify_otp == false || existsUser.role == 'admin') {

            const otp = request.email == 'kishan@auxanoglobalservices.com' ? '111111' : Math.floor(100000 + Math.random() * 900000);
            existsUser['otp'] = otp.toString();
            existsUser['otp_time'] = new Date();

            this.sendNotificationAndEmail(existsUser, 'verify_otp_email', {
                metadata: { otp: otp.toString() },
            });
            access_token = "";
            if (existsUser.role == 'admin') {
                existsUser['two_factor_auth'] = true;
            }
        }

        const { created_at, updated_at, deleted_at, otp, otp_time, password, ...modifiedUser } = existsUser;

        existsUser['language'] = lang;
        existsUser['remember_me'] = request.remember_me;

        await this.Users.save(existsUser);
        return {
            ...modifiedUser,
            profile_path: process.env.AWS_FILE_PATH + 'images/profile/',
            campaign_path: process.env.AWS_FILE_PATH + 'files/campaign/',
            campaign_receipt_path: process.env.AWS_FILE_PATH + 'files/campaign/receipt/',
            draft_path: process.env.AWS_FILE_PATH + 'files/draft/',
            dispute_path: process.env.AWS_FILE_PATH + 'files/dispute/',
            advertisement_path: process.env.AWS_FILE_PATH + 'images/advertisement/',
            bank_path: process.env.AWS_FILE_PATH + 'images/bank/',
            access_token: access_token,
            // profile_path : process.env.AWS_PROFILE_FILE_PATH,
        };

    }

    async socialLogin(request: SocialLoginDto) {
        const lang = request.language_code || 'en';
        const existsUser = await this.Users.findOne({ where: { email: request.email } });
        if (!existsUser) {
            throw new HttpException(responseMessages[lang].user.user_not_exists, HttpStatus.NO_CONTENT);
        }

        if (!existsUser.social_id && request.is_link == false) {
            return { is_link: true };
        }

        // if (existsUser.social_id != null && existsUser.social_id != request.social_id) {
        //     throw new HttpException(responseMessages[lang].user.user_not_exists, HttpStatus.BAD_REQUEST);
        // }

        const { created_at, updated_at, deleted_at, otp, otp_time, password, ...modifiedUser } = existsUser;

        const payload = { sub: existsUser.id, username: existsUser.email };
        let access_token = await this.jwtService.sign(payload);
        existsUser['first_name'] = request.first_name;
        existsUser['last_name'] = request.last_name || '';
        existsUser['language'] = lang;
        existsUser['social_id'] = request.social_id
        await this.Users.save(existsUser);

        return {
            ...modifiedUser,
            profile_path: process.env.AWS_FILE_PATH + 'images/profile/',
            campaign_path: process.env.AWS_FILE_PATH + 'files/campaign/',
            campaign_receipt_path: process.env.AWS_FILE_PATH + 'files/campaign/receipt/',
            draft_path: process.env.AWS_FILE_PATH + 'files/draft/',
            dispute_path: process.env.AWS_FILE_PATH + 'files/dispute/',
            advertisement_path: process.env.AWS_FILE_PATH + 'images/advertisement/',
            bank_path: process.env.AWS_FILE_PATH + 'images/bank/',
            access_token: access_token,
            // profile_path : process.env.AWS_PROFILE_FILE_PATH,
        };
    }

    async socialLoginUpdate(request, auth) {
        const lang = auth.language || 'en';
        const existsUser = await this.Users.findOne({ where: { social_id: request.social_id, id: Not(auth.id) } });
        if (existsUser) {
            throw new HttpException(responseMessages.en.user.social_id_exists, HttpStatus.BAD_REQUEST);
        }

        auth['social_id'] = request.social_id
        await this.Users.save(auth);

        return { social_id: request.social_id };
    }

    /**
     * Retrieves a user details based on user id.
     */
    async self(authUser: any) {
        let user = await this.userService.getUserDetails(authUser, authUser);
        user['invited_count'] = 0;
        if (authUser.role == UserRoles.INFLUENCER) {
            user['invited_count'] = await this.CampaignInfluencer.createQueryBuilder('campaignInfluencer')
                .innerJoin('campaignInfluencer.campaign', 'campaign')
                .where('campaignInfluencer.influencer = :influencerIds', { influencerIds: user.id })
                .andWhere('campaignInfluencer.influencer_status = :status', { status: InfluencerStatus.WAITING_FOR_QUOTATIONS })
                .andWhere('campaign.deleted_at IS NULL')
                .getCount();
        }
        user['profile_path'] = process.env.AWS_FILE_PATH + 'images/profile/';
        user['campaign_path'] = process.env.AWS_FILE_PATH + 'files/campaign/';
        user['campaign_receipt_path'] = process.env.AWS_FILE_PATH + 'files/campaign/receipt/',
            user['draft_path'] = process.env.AWS_FILE_PATH + 'files/draft/';
        user['dispute_path'] = process.env.AWS_FILE_PATH + 'files/dispute/';
        user['advertisement_path'] = process.env.AWS_FILE_PATH + 'images/advertisement/';
        user['bank_path'] = process.env.AWS_FILE_PATH + 'images/bank/';
        user['country_obj'] = await this.Countries.findOne({ where: { two_digit_code: user.country } });

        return user;
    }

    async getClientIp(req: any) {
        return (
            req.headers['x-forwarded-for']?.toString().split(',')[0] ||
            req.connection?.remoteAddress ||
            req.socket?.remoteAddress ||
            ''
        );
    }

    async getUserDetails(params: any, req: any) {
        const existsUser = await this.Users.findOne({ where: { slug: params.slug } });
        if (!existsUser) {
            throw new HttpException(responseMessages.en.user.user_not_exists, HttpStatus.NOT_FOUND);
        }
        const ip = await this.getClientIp(req);
        console.log('ip', ip);
        let guestUser = await this.GuestUserProfileAccess.findOne({ where: { ip: ip } });
        if (!guestUser) {
            guestUser = new GuestUserProfileAccess();
            guestUser.ip = ip;
            guestUser.remaining_count = Constants.GUEST_PROFILE_ACCESS.LIMIT;
            guestUser.expire_at = moment().add(Constants.GUEST_PROFILE_ACCESS.DAYS, 'days').toDate();
        }
        if (moment().isAfter(guestUser.expire_at)) {
            guestUser.expire_at = moment().add(Constants.GUEST_PROFILE_ACCESS.DAYS, 'days').toDate();
            guestUser.remaining_count = Constants.GUEST_PROFILE_ACCESS.LIMIT;
        }
        guestUser.remaining_count = guestUser.remaining_count ? (guestUser.remaining_count - 1) : 0;
        await this.GuestUserProfileAccess.save(guestUser);

        let data = { slug: existsUser.slug, first_name: existsUser.first_name, last_name: existsUser.last_name, about_me: existsUser.about_me, ai_summary: existsUser.ai_summary, image: existsUser.image };
        if (guestUser.remaining_count > 0) {
            data = await this.userService.getUserDetails(existsUser, req?.user);
        }
        return {
            data: data,
            is_blurred: guestUser.remaining_count <= 0 ? true : false,
            remaining_count: guestUser.remaining_count,
        }
    }


    async changePassword(request: any, authUser: any) {
        const existsUser = await this.Users.findOne({ where: [{ id: authUser.id }] });
        if (!existsUser) {
            throw new HttpException(responseMessages.en.user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        const comparedPass = await bcrypt.compare(request.old_password, existsUser.password);

        if (!comparedPass) {
            throw new HttpException(responseMessages.en.user.old_password_incorrect, HttpStatus.BAD_REQUEST);
        }

        existsUser['password'] = await bcrypt.hash(request.password, Constants.salt_rounds);

        await this.Users.save(existsUser);

        return;
    }

    async changeLanguage(request: any, authUser: any) {
        const existsUser = await this.Users.findOne({ where: [{ id: authUser.id }] });
        if (!existsUser) {
            throw new HttpException(responseMessages.en.user.user_not_exists, HttpStatus.NOT_FOUND);
        }
        existsUser['language'] = request.language_code;
        await this.Users.save(existsUser);
        return;
    }

    /**
     * Deletes a user based on the provided query and request parameters.
     */
    async delete(query, authUser) {
        const userToDelete = authUser.role === UserRoles.ADMIN && query.id
            ? await this.Users.findOne({ where: { id: query.id } })
            : authUser;

        if (!userToDelete) {
            throw new HttpException(responseMessages.en.user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        if (userToDelete.role === UserRoles.ADMIN) {
            throw new HttpException(responseMessages.en.user.admin_account_delete_error, HttpStatus.BAD_REQUEST);
        }

        const response = await this.userService.delete(userToDelete);
        console.log('response1', response);
        if (response.status) {
            return response;
        }
        throw new HttpException(response.message, HttpStatus.BAD_REQUEST);
    }

    async multiDelete(body) {
        for (const id of body.ids) {
            const userToDelete = await this.Users.findOne({ where: { id } });
            if (!userToDelete || userToDelete.role === UserRoles.ADMIN) {
                continue;
            }
            await this.userService.delete(userToDelete);
        }
    }

    async logout(request: any, authUser: any) {
        // const authHeader = request.headers.authorization;

        // if (authHeader) {
        //     // const payload = { sub: authUser.id, username: authUser.email };
        //     // let access_token = await this.jwtService.sign(payload);
        //     const token = authHeader.split(' ')[1];
        //     const decodedToken = await this.jwtService.decode(token)

        //     // tokenBlacklist.add(token); // Add token to the blacklist
        //     console.log(decodedToken);
        // }

        // await this.authRepository.deleteLogin(request,user)
        return;
    }


    async forgotPassword(request: ForgotPasswordDto) {
        const lang = request.language || 'en';
        const existsUser = await this.Users.createQueryBuilder('user')
            .where('LOWER(user.email) = LOWER(:email)', { email: request.email })
            .getOne();

        if (!existsUser) {
            throw new HttpException(responseMessages[lang].user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        const otp = Math.floor(100000 + Math.random() * 900000);
        existsUser['otp'] = otp.toString();
        existsUser['otp_time'] = new Date(),
            existsUser['language'] = lang;
        await this.Users.save(existsUser);

        this.sendNotificationAndEmail(existsUser, 'verify_otp_email', {
            metadata: { otp: otp.toString() },
        });

        return;

    }

    async resetPassword(request: ResetPasswordDto) {
        const lang = request.language || 'en';
        const existsUser = await this.Users.createQueryBuilder('user')
            .where('LOWER(user.email) = LOWER(:email)', { email: request.email })
            .getOne();
        if (!existsUser) {
            throw new HttpException(responseMessages[lang].user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        existsUser['password'] = await bcrypt.hash(request.password, Constants.salt_rounds);
        existsUser['language'] = lang;
        await this.Users.save(existsUser);

        return;
    }

    async saveError(body, authUser) {
        let { module = 'UNKNOWN', name = 'UNKNOWN', message = 'UNKNOWN', context } = body
        if (typeof context !== 'object' || context === null || Array.isArray(context)) {
            context = {};
        }

        context.user = { id: authUser.id, email: authUser.email, name: authUser.first_name };
        await this.errorLogService.logError(module, name, message, context);
    }

    async verifyWhatsApp(request: VerifyWhatsAppDto, authUser: any) {
        const existsUser = await this.Users.findOne({ where: { id: authUser.id } });
        if (!existsUser) {
            throw new HttpException(responseMessages.en.user.user_not_exists, HttpStatus.NOT_FOUND);
        }

        const mobileNumberExists = await this.Users.findOne({ where: { phone_number: request.phone_number, id: Not(authUser.id), is_whatsapp_verified: true } });
        if (mobileNumberExists) {
            throw new HttpException(responseMessages.en.user.phone_number_exists, HttpStatus.BAD_REQUEST);
        }
        let phoneNumber = request.phone_number
        if (phoneNumber.startsWith('0')) {
            phoneNumber = phoneNumber.substring(1);
        }
        phoneNumber = `${request.country_code}${phoneNumber}`.replace('+', '');
        this.whatsappService.verifyWhatsAppNumber(phoneNumber, `${existsUser.first_name}`);
        existsUser['phone_number'] = request.phone_number;
        existsUser['whatsapp_request_at'] = new Date();
        existsUser['country_code'] = request.country_code;
        existsUser['whatsapp_phone_number'] = phoneNumber;
        existsUser['is_whatsapp_verified'] = null;
        await this.Users.save(existsUser);
        return;
    }

}
