// const _ = require('lodash');
// require('dotenv').config()
// const mongoose = require("mongoose");
// const { Admin } = require('../../Models/admin');
// const { LoginUser } = require('../../Models/login-user');
// const { Category } = require('../../models/admin/category');
export { };
const _ = require('lodash');
require('dotenv').config({ path: __dirname + '../.env' })
const { Category } = require("../../models/admin/category")
const mongoose = require("mongoose");
const { Admin } = require('../../models/admin/admin');
const { dateFormat } = require('../../core/utilities/commonService');
const { sendEmail } = require('../../core/utilities/emailService');
const { apiResponse } = require("../../core/response/response")
const { SUCCESS, REDIRECTION, CLIENT_ERROR, SERVER_ERROR } = require("../../core/response/statusCode")
const { ERROR_MSG, SUCCESS_MSG } = require("../../core/response/messages")
const { forgotPasswordTemplate } = require('../../core/email-templates/email-admin');
const adminUserObject = new Admin();
export { };

exports.login = async (req, res) => {
    let lang = 'en';
    // If no validation errors, get the req.body objects that were validated and are needed
    const { email, password } = req.body

    let adminInformation = await Admin.findOne({ "email": email, is_deleted : false }, { first_name: 1, last_name: 1, email: 1, salt_key: 1, created_at: 1, password: 1, is_active: 1, is_super_admin: 1 })

    if (!adminInformation) return apiResponse(res, true, [], ERROR_MSG[`ACCOUNT-NOT-EXIST-${lang}`], CLIENT_ERROR.badRequest, 0, [], req);


    //checking password match
    const isValidPassword = await adminUserObject.passwordCompare(adminInformation.salt_key, adminInformation.password, req.body.password);

    if (!isValidPassword) return apiResponse(res, true, [], ERROR_MSG[`PASSWORD-MISMATCH-${lang}`], CLIENT_ERROR.badRequest, 0, [], req);

    if (!adminInformation['is_active']) return apiResponse(res, true, [], ERROR_MSG[`USER-NOT-ACTIVE-${lang}`], CLIENT_ERROR.badRequest, 0, [], req);



    const token = await adminUserObject.generateToken(adminInformation.salt_key);//generate token

    await Admin.findOneAndUpdate({ _id: adminInformation._id }, { $set: { auth_token: token } }, { new: true })


    let userData = _.pick(adminInformation, ['_id', 'first_name', 'last_name', 'email', 'is_active', 'is_super_admin'])
    res.setHeader('auth_token', token);
    res.header('Access-Control-Expose-Headers', 'auth-token')
    userData['auth_token'] = token;
    userData['password'] = null;
    userData['salt_key'] = null;

    return apiResponse(res, false, [], '', SUCCESS.OK, 0, userData, req);

}

exports.forgotPassword = async (req, res) => {

    let lang = 'en';
    // If no validation errors, get the req.body objects that were validated and are needed
    const { email } = req.body

    //checking unique email
    let adminInformation = await Admin.findOne(
        { email: email },
        { email: 1, first_name: 1, last_name: 1 }
    );
    if (!adminInformation) return apiResponse(res, true, [], ERROR_MSG[`ACCOUNT-NOT-REGISTERD-${lang}`], CLIENT_ERROR.badRequest, 0, [])

    const resetPasswordToken = await adminUserObject.generateResetPasswordToken(adminInformation.salt_key);//generate reset password token 

    await Admin.findOneAndUpdate({ email: adminInformation.email }, { $set: { reset_password_token: resetPasswordToken, updatedAt: new Date() } }, { new: true })
    let fullName = `${adminInformation.first_name} ${adminInformation.last_name}`
    const link = `${process.env.WEB_ENDPOINT_ADMIN}/auth/reset-password/${resetPasswordToken}`

    let templateData = forgotPasswordTemplate({ fullName, link })
    const mailOptions = {
        to: adminInformation.email,
        subject: templateData.subject,
        html: templateData.html
    };
    sendEmail(mailOptions, res);

    return apiResponse(res, false, [], '', SUCCESS.OK, 0, [adminInformation], req)
}

exports.updatePassword = async (req, res) => {

    let lang = 'en';
    // If no validation errors, get the req.body objects that were validated and are needed
    const { token, password } = req.body

    //checking unique email
    let existingUser = await Admin.findOne(
        { reset_password_token: token },
        { _id: 1, email: 1, password: 1, salt_key: 1, createdAt: 1 }
    );

    if (!existingUser) return apiResponse(res, true, [], ERROR_MSG[`ACCOUNT-NOT-REGISTERD-${lang}`], CLIENT_ERROR.badRequest, [])
    if (!password) return apiResponse(res, true, [], ERROR_MSG[`PASSWORD-NOT-EMPTY-${lang}`], CLIENT_ERROR.badRequest, []);
    const encryptedPassword = await adminUserObject.encryptPassword(existingUser, password);//encrypted password

    if (encryptedPassword == existingUser.password) {
        return apiResponse(res, true, [], ERROR_MSG[`USE-ANOTHER-PASSWORD-${lang}`], CLIENT_ERROR.badRequest, 0, [])
    }

    await Admin.findOneAndUpdate({ email: existingUser.email }, { $set: { password: encryptedPassword, updatedAt: new Date(), reset_password_token: '' } }, { new: true })

    return apiResponse(res, true, [], '', SUCCESS.OK, 0, [existingUser], req)
}


exports.adminInfo = async (req, res) => {
    const { id } = req.body
    let lang = 'en';
    let condition = {}
    condition['_id'] = id;
    //checking unique email
    let adminInformation = await Admin.findOne(
        condition, { first_name: 1, last_name: 1, is_active: 1, is_super_admin: 1, is_deleted: 1, auth_token: 1, email:1, profile_pic:1 }
    );
    if (!adminInformation) return apiResponse(res, true, [], ERROR_MSG[`ACCOUNT-NOT-EXIST-${lang}`], CLIENT_ERROR.badRequest, 0, [], req);
    return apiResponse(res, false, [], '', SUCCESS.OK, 0, adminInformation, req);
}

exports.updateAdmin = async (req, res) => {
    // If no validation errors, get the req.body objects that were validated and are needed

    let lang1 = 'en';

    const { id, email, first_name, last_name, profile_pic } = req.body;

    let condition = {}
    condition['_id'] = new mongoose.Types.ObjectId(id);

    //checking record exist
    let record = await Admin.findOne(condition, { _id: 1 });

    if (!record) return apiResponse(res, true, [], ERROR_MSG[`NO-RECORD-FOUND-${lang1}`], SERVER_ERROR.internalServerError, 0, [], req);
    
    //update admin info
    const updateAdmin = await Admin.findOneAndUpdate({ _id: new mongoose.Types.ObjectId(req.body.id) }, { $set: req.body }, { new: true });
    return apiResponse(res, false, [], '', SUCCESS.OK, 0, [updateAdmin], req);
}

exports.changePassword = async (req, res) => {
    //  If no validation errors, get the req.body objects that were validated and are needed

    let lang1 = 'en';
    const { id, oldPassword, Password } = req.body

    //checking unique email
    let existingUser = await Admin.findOne(
        { _id: new mongoose.Types.ObjectId(id), is_deleted : false },
        { _id: 1, email: 1, password: 1, salt_key: 1, createdAt: 1 }
    );

    if (!existingUser) return apiResponse(res, true, [], ERROR_MSG[`NO-RECORD-FOUND-${lang1}`], SERVER_ERROR.internalServerError, 0, [], req)

    const encryptedOldPassword = await adminUserObject.encryptPassword(existingUser, oldPassword);//encrypted password

    if (encryptedOldPassword != existingUser.password) 
        return apiResponse(res, true, [], ERROR_MSG[`OLD-PASSWORD-NOT-MATCHED-${lang1}`], CLIENT_ERROR.badRequest, 0, [], req)

    const encryptedPassword = await adminUserObject.encryptPassword(existingUser, Password);//encrypted password

    if (encryptedPassword == existingUser.password) {
        return apiResponse(res, true, [], ERROR_MSG[`USE-ANOTHER-PASSWORD-${lang1}`], CLIENT_ERROR.badRequest, 0, [])
    }

    await Admin.findOneAndUpdate({ email: existingUser.email, is_deleted : false }, { $set: { password: encryptedPassword, updatedAt: new Date() } }, { new: true })

    return apiResponse(res, false, [], '', SUCCESS.OK, 0, [existingUser],req);
}
