"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthController = void 0;
const ResponseHelper_1 = require("../../helpers/ResponseHelper");
const Auth_1 = require("../../Utils/Auth");
const Admin_1 = require("../../models/Admin");
const MailHelper_1 = require("../../helpers/MailHelper");
const EmailTemplate_1 = require("../../models/EmailTemplate");
const AppSetting_1 = require("../../models/AppSetting");
const Settings_1 = require("../../models/Settings");
const Helper_1 = require("../../helpers/Helper");
const ImageService_1 = require("../../services/ImageService");
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
app.use(cookieParser());
class AuthController {
    static login(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const startTime = new Date().getTime();
            const { email, password, fcm_token } = req.body;
            try {
                let isUserExist = yield Admin_1.default.findOne({
                    email: email,
                });
                if (!isUserExist) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Please enter the correct email", isUserExist, startTime);
                }
                const isPasswordValid = yield Auth_1.default.comparePassword(password, isUserExist.password);
                if (!isPasswordValid) {
                    return ResponseHelper_1.default.badRequest(res, "BADREQUEST", "Invalid password", {}, startTime);
                }
                isUserExist.device_token = fcm_token !== null && fcm_token !== void 0 ? fcm_token : isUserExist.device_token;
                isUserExist.device_type = "web";
                const payload = {
                    id: isUserExist._id,
                    email: isUserExist.email,
                };
                yield isUserExist.save();
                const token = yield Auth_1.default.getToken(payload, "1d", next);
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Login successfully", { user: isUserExist, token }, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static signUp(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const startTime = new Date().getTime();
            const { email, password, name, phoneNumber } = req.body;
            try {
                let user = yield Admin_1.default.findOne({
                    $and: [{ email: email }],
                });
                if (!user) {
                    user = yield Admin_1.default.create({
                        email: "admin@yopmail.com",
                        password: yield Auth_1.default.encryptPassword("123456"),
                        name: "Admin",
                        phoneNumber: "919632587412",
                    });
                    return ResponseHelper_1.default.created(res, "CREATED", "SignUp sucessfully");
                }
                return ResponseHelper_1.default.conflict(res, "CONFLICT", "User already exist with this email", user, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static getProfile(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const startTime = new Date().getTime();
            try {
                let getAdmin = yield Admin_1.default.findOne({
                    _id: req.user.id,
                });
                if (!getAdmin) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "User does not exist", getAdmin, startTime);
                }
                console.log(getAdmin);
                getAdmin.image = getAdmin.image
                    ? Helper_1.default.generateAssetUrl(req, getAdmin.image)
                    : "";
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Get Profile Successfully", getAdmin, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static changePassword(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const startTime = new Date().getTime();
            const { old_password, new_password } = req.body;
            try {
                const admin = yield Admin_1.default.findById(req.user.id);
                const isPasswordCurrentCorrect = yield Auth_1.default.comparePassword(old_password, admin.password);
                if (!isPasswordCurrentCorrect) {
                    return ResponseHelper_1.default.badRequest(res, "BADREQUEST", "Old password does not match", {}, startTime);
                }
                const isSamePassword = yield Auth_1.default.comparePassword(new_password, admin.password);
                if (isSamePassword) {
                    return ResponseHelper_1.default.badRequest(res, "BADREQUEST", "New password cannot be the same as the old password", {}, startTime);
                }
                const encryptedPassword = yield Auth_1.default.encryptPassword(new_password);
                admin.password = encryptedPassword;
                yield admin.save();
                var emailTemplate = yield EmailTemplate_1.default.findOne({
                    slug: "change-password",
                });
                if (!emailTemplate) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Change password email template not found", {}, new Date().getTime());
                }
                var replacedHTML = emailTemplate.description;
                replacedHTML = replacedHTML.replace("[NAME]", admin.name || "");
                yield MailHelper_1.default.sendMail(admin.email, emailTemplate.title, replacedHTML);
                return ResponseHelper_1.default.ok(res, "SUCCESS", "password changed successfully", {}, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static updateProfile(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const startTime = new Date().getTime();
            const { email, name } = req.body;
            try {
                let getAdmin = yield Admin_1.default.findOne({
                    _id: req.user.id,
                });
                if (!getAdmin) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "User does Not Exist", getAdmin, startTime);
                }
                (getAdmin.name = name ? name : getAdmin.name),
                    (getAdmin.email = email ? email : getAdmin.email),
                    yield getAdmin.save();
                getAdmin.image = getAdmin.image
                    ? Helper_1.default.generateAssetUrl(req, getAdmin.image)
                    : "";
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Update Profile Successfully", getAdmin, startTime);
            }
            catch (error) {
                next(error);
            }
        });
    }
    static updateProfileImage(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const startTime = new Date().getTime();
                let getAdmin = yield Admin_1.default.findOne({
                    _id: req.user.id,
                });
                if (!getAdmin) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Admin not found", getAdmin, startTime);
                }
                if (req.file) {
                    const imageFullPath = yield ImageService_1.default.uploadImageLocally(req, res, next, `admins/${getAdmin.id}/profile`);
                    if (imageFullPath) {
                        getAdmin.image = imageFullPath !== null && imageFullPath !== void 0 ? imageFullPath : "";
                        yield getAdmin.save();
                    }
                    getAdmin.image = Helper_1.default.generateAssetUrl(req, getAdmin.image);
                }
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Image updated successfully", getAdmin, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static removeProfileImage(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const startTime = new Date().getTime();
                const getAdmin = yield Admin_1.default.findOne({ _id: req.params.id });
                if (!getAdmin) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Admin not found", getAdmin, startTime);
                }
                if (getAdmin.image) {
                    yield ImageService_1.default.deleteImageLocally(`admins/${getAdmin.id}/profile`, getAdmin.image);
                    getAdmin.image = "";
                    yield getAdmin.save();
                }
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Image removed successfully", getAdmin, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static getSetting(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const startTime = new Date().getTime();
                const getSetting = yield Settings_1.default.findOne().sort({ _id: -1 });
                if (!getSetting) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Setting does Not Exist", {}, startTime);
                }
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Setting Get Successfully", getSetting, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static updateSetting(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const startTime = new Date().getTime();
                const { radius, tariff_charge } = req.body;
                const getSetting = yield Settings_1.default.findOne().sort({ _id: -1 });
                if (!getSetting) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Setting does Not Exist", {}, startTime);
                }
                getSetting.radius = radius ? radius : getSetting.radius;
                getSetting.tariff_charge = tariff_charge
                    ? tariff_charge
                    : getSetting.tariff_charge;
                getSetting.save();
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Setting Updated Successfully", getSetting, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
    static forgotPassword(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const email = req.body.email;
            try {
                let admin = yield Admin_1.default.findOne({ email: email });
                if (!admin) {
                    let msg = "Email address is not exists with us. Please check again";
                    return ResponseHelper_1.default.notFound(res, "SUCCESS", msg, admin, new Date().getTime());
                }
                const otp = yield Auth_1.default.generateOtp();
                admin.otp = otp === null || otp === void 0 ? void 0 : otp.otp;
                yield admin.save();
                var emailTemplate = yield EmailTemplate_1.default.findOne({
                    slug: "forgot-password",
                });
                if (!emailTemplate) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Forget password email template not found", {}, new Date().getTime());
                }
                var replacedHTML = emailTemplate.description;
                replacedHTML = replacedHTML.replace("[NAME]", admin.name || "");
                replacedHTML = replacedHTML.replace("[OTP]", admin.otp || "");
                yield MailHelper_1.default.sendMail(admin.email, emailTemplate.title, replacedHTML);
                return ResponseHelper_1.default.ok(res, "SUCCESS", "OTP has been sent to your email, please check your inbox", {}, new Date().getTime());
            }
            catch (error) {
                next(error);
            }
        });
    }
    static verifyOtp(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const email = req.body.email;
            const otp = req.body.otp;
            try {
                let admin = yield Admin_1.default.findOne({ email: email });
                if (!admin) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "not found", {}, new Date().getTime());
                }
                if (admin.otp != otp) {
                    return ResponseHelper_1.default.badRequest(res, "BADREQUEST", "Invalid OTP", {}, new Date().getTime());
                }
                admin.otp = null;
                admin.otp_expiry_time = null;
                admin.save();
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Please check mail id , send otp on mail", {}, new Date().getTime());
            }
            catch (error) {
                next(error);
            }
        });
    }
    static resetPassword(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const { email, password } = req.body;
            const startTime = new Date().getTime();
            try {
                let user = yield Admin_1.default.findOne({ email });
                if (!user) {
                    return ResponseHelper_1.default.notFound(res, "notFound", "User not found", {}, startTime);
                }
                user.password = yield Auth_1.default.encryptPassword(password);
                yield user.save();
                var emailTemplate = yield EmailTemplate_1.default.findOne({
                    slug: "change-password",
                });
                if (!emailTemplate) {
                    return ResponseHelper_1.default.notFound(res, "NOTFOUND", "Change password email template not found", {}, new Date().getTime());
                }
                var replacedHTML = emailTemplate.description;
                replacedHTML = replacedHTML.replace("[NAME]", user.name || "");
                yield MailHelper_1.default.sendMail(user.email, emailTemplate.title, replacedHTML);
                return ResponseHelper_1.default.ok(res, "SUCCESS", "Password changed successfully.", {}, startTime);
            }
            catch (error) {
                next(error);
            }
        });
    }
    static updateAppSetting(req, res, next) {
        return __awaiter(this, void 0, void 0, function* () {
            const startTime = new Date().getTime();
            const { app_store_url, play_store_url, android_version, ios_version, android_share_content, ios_share_content, } = req.body;
            try {
                let getSetting = yield AppSetting_1.default.findOne().sort({ _id: -1 });
                if (!getSetting) {
                    const data = {
                        app_store_url: app_store_url,
                        play_store_url: play_store_url,
                        android_version: android_version,
                        ios_version: ios_version,
                        android_share_content: android_share_content,
                        ios_share_content: ios_share_content,
                    };
                    const setting = yield new AppSetting_1.default(data).save();
                    return ResponseHelper_1.default.ok(res, "SUCCESS", "App setting has been added successfully", setting, startTime);
                }
                (getSetting.app_store_url = app_store_url
                    ? app_store_url
                    : getSetting.app_store_url),
                    (getSetting.play_store_url = play_store_url
                        ? play_store_url
                        : getSetting.play_store_url),
                    (getSetting.android_version = android_version
                        ? android_version
                        : getSetting.android_version),
                    (getSetting.ios_version = ios_version
                        ? ios_version
                        : getSetting.ios_version),
                    (getSetting.android_share_content = android_share_content
                        ? android_share_content
                        : getSetting.android_share_content),
                    (getSetting.ios_share_content = ios_share_content
                        ? ios_share_content
                        : getSetting.ios_share_content),
                    getSetting.save();
                return ResponseHelper_1.default.ok(res, "SUCCESS", "App setting has been updated successfully", getSetting, startTime);
            }
            catch (err) {
                next(err);
            }
        });
    }
}
exports.AuthController = AuthController;
