const userFunction = require("../functions/user");
const validationFunction = require("../functions/validation");
const otpFunction = require("../functions/otp");
const emailFunction = require("../functions/email");
const jwt = require("jsonwebtoken");
const userModel = require("../models/user");
require("dotenv").config();

// const signup = async (req, res) => {
//     try {
//         console.log("first :", req.files);
//         return
//         const validate = await validationFunction.validateUser(req);
//         if(validate){
//             return res.status(200).json({
//                 success: false,
//                 msg: "Email is Already Taken!"
//             })
//         } else {
//             const { type, fullName, phone, email, password} = req.body;
//             const token = jwt.sign({
//                 type,
//                 fullName,
//                 phone,
//                 email: req.body.email?.toLowerCase(),
//                 password,
//             }, process.env.SECRET_KEY, { expiresIn: "1y"});

//             const createOTP = await otpFunction.generateOTP(req);
//             const userData = {
//                 email: createOTP.email,
//                 OTP: createOTP.OTP,
//                 signupToken: token
//             };
//             const sendEmail = await emailFunction.sendOTP(userData);
//             return res.status(200).json({
//                 success: true,
//                 msg: "OTP is Sent!",
//                 data: userData
//             });
//         }
//     } catch (error) {
//         console.log("Having Errors:", error);
//         return res.status(403).json({
//             success: false,
//             msg: "Something Went Wrong!",
//             error: error.message
//         })
//     }
// };

const signup = async (req, res) => {
    try {
        const validate = await validationFunction.validateUser(req);
        if (validate) {
            return res.status(200).json({
                success: false,
                msg: "Email is Already Taken!"
            })
        } else {
            let token = {};
            if (req.body.type === "Technician") {
                const { type, fullName, ss, DOB, locationName, email, password } = req.body;
                const imagePaths = req.files.map(file => file.filename);
                token = jwt.sign({
                    type,
                    fullName,
                    ss,
                    DOB,
                    locationName,
                    pestControlLicense: imagePaths,
                    email: req.body.email?.toLowerCase(),
                    password,
                }, process.env.SECRET_KEY, { expiresIn: "1y" });
            };
            if (req.body.type === "User") {
                const { type, fullName, locationName, email, password } = req.body;
                token = jwt.sign({
                    type,
                    fullName,
                    locationName,
                    email: req.body.email?.toLowerCase(),
                    password
                }, process.env.SECRET_KEY, { expiresIn: "1y" })
            };
            const createOTP = await otpFunction.generateOTP(req);
            const userData = {
                email: createOTP.email,
                OTP: createOTP.OTP,
                signupToken: token
            };

            const sendEmail = await emailFunction.sendOTP(userData);
            return res.status(200).json({
                success: true,
                msg: "OTP is Sent!",
                data: userData
            });
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const verifyOTP = async (req, res) => {
    try {
        const verify = await otpFunction.verifyOTP(req);
        if (!verify) {
            return res.status(200).json({
                success: false,
                msg: "Invalid OTP!"
            })
        } else {
            const { signupToken } = req.body;
            const decode = jwt.verify(signupToken, process.env.SECRET_KEY);
            const user = await userFunction.signup(decode);
            // return
            req.body.userId = user._id;
            const userData = await userFunction.getUserData(req);;
            const token = jwt.sign({
                type: user.type,
                _id: user._id,
                email: user.email,
                // phone: user.phone
            }, process.env.SECRET_KEY, { expiresIn: "1y" });

            return res.status(200).json({
                success: true,
                msg: "User Signed-Up Successfully!",
                data: userData,
                accessToken: token
            });
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const login = async (req, res) => {
    try {
        const validate = await validationFunction.validateUser(req);
        if (!validate) {
            return res.status(200).json({
                success: false,
                msg: "No Account Found!"
            })
        } else {
            const user = await userFunction.getUser(req);
            if (user.isDeleted === true) {
                return res.status(200).json({
                    success: false,
                    msg: "Can Not Login Account is Deleted!"
                })
            } else {
                const { password } = req.body;
                const hash = user.password;
                const verify = await validationFunction.verifyPassword(password, hash);
                if (!verify) {
                    return res.status(200).json({
                        success: false,
                        msg: "Invalid Credentials!"
                    })
                } else {
                    const token = jwt.sign({
                        type: user.type,
                        _id: user._id,
                        email: user.email,
                        phone: user.phone
                    }, process.env.SECRET_KEY, { expiresIn: "1y" });

                    req.body.userId = user._id;
                    const userData = await userFunction.getUserData(req);
                    console.log("first :", userData);

                    return res.status(200).json({
                        success: true,
                        msg: "User Logged-In Successfully!",
                        data: userData,
                        accessToken: token
                    })
                }
            }
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const googleLogin = async (req, res) => {
    try {
        const { googleId, fullName, email, profileImage } = req.body;

        if (!googleId) return res.status(400).json({ success: false, msg: "googleId are required" });
        if (!fullName) return res.status(400).json({ success: false, msg: "fullName are required" });
        if (!email) return res.status(400).json({ success: false, msg: "email are required" });
        if (!profileImage) return res.status(400).json({ success: false, msg: "profile image are required" });

        const user = await userModel.findOne({ googleId });
        if (user) {
            if (user.isDeleted) return res.status(403).json({ success: false, msg: "Your account has been deleted. Please contact support." });

            const token = jwt.sign({
                type: user.type,
                _id: user._id,
                email: user.email,
                phone: user.phone
            }, process.env.SECRET_KEY, { expiresIn: "1y" });
            return res.status(200).json({ success: true, msg: "Google login successful", token, user, isExist: true })
        }
        const emailExists = await userModel.findOne({ email });

        if (emailExists) return res.status(400).json({ success: false, msg: "Email already exists" });
        const newUser = await userModel.create({
            googleId, fullName, email,
            profileImage, isGoogleUser: true, type: ""
        });

        const token = jwt.sign({
            _id: newUser._id,
            email: newUser.email,
        }, process.env.SECRET_KEY, { expiresIn: "1d" });
        res.status(200).json({ success: true, msg: "Google login successful", isExist: false, token });

    } catch (error) {
        console.log(error);
        return res.status(403).json({
            success: false, msg: "Something Went Wrong!", error: error.message
        })
    }
}

const setUserType = async (req, res) => {
    try {
        const { type } = req.body;
        const _id = req.user._id

        if (!_id) return res.status(400).json({ success: false, msg: "userId are required" });
        if (!type) return res.status(400).json({ success: false, msg: "Type are required" });

        const user = await userModel.findById(_id);

        if (!user) return res.status(404).json({ success: false, msg: "User not found" });

        if (user.type && user.type !== "") {
            return res.status(200).json({ success: true, msg: "User type already set" });
        }

        user.type = type;
        await user.save();

        const token = jwt.sign({
            type: user.type,
            _id: user._id,
            email: user.email,
            phone: user.phone
        }, process.env.SECRET_KEY, { expiresIn: "1y" });

        res.status(200).json({ success: true, msg: "User type updated", user, token });

    } catch (error) {
        console.error(error);
        res.status(500).json({ success: false, msg: "Something went wrong", error: error.message });
    }
}

const userProfile = async (req, res) => {
    try {
        const user = await userFunction.getUserById(req);
        if (!user) {
            return res.status(200).json({
                success: false,
                msg: "No Profile Found By Id!"
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "User Profile Details!",
                data: user
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const getAllUsers = async (req, res) => {
    try {
        const users = await userFunction.getAllUsers(req);
        if (users.length === 0) {
            return res.status(200).json({
                success: false,
                msg: "No Users Found!"
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "All Users!",
                data: users
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const updateUser = async (req, res) => {
    try {
        const user = await userFunction.updateUser(req);
        if (!user) {
            return res.status(200).json({
                success: false,
                msg: "No User Found to Update!"
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "User Updated Successfully!",
                data: user
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const forgetPassword = async (req, res) => {
    try {
        const validate = await validationFunction.validateUser(req);
        if (!validate) {
            return res.status(200).json({
                success: false,
                msg: "No User Found!"
            })
        } else {
            const user = await userFunction.getUser(req);
            const createOTP = await otpFunction.generateOTP(req);
            const userData = {
                _id: user._id,
                email: createOTP.email,
                OTP: createOTP.OTP
            };

            const sendEmail = await emailFunction.sendOTP(userData);
            return res.status(200).json({
                success: true,
                msg: "OTP is Sent!",
                data: userData
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const verifyOTPForPassword = async (req, res) => {
    try {
        const verify = await otpFunction.verifyOTP(req);
        if (!verify) {
            return res.status(200).json({
                success: false,
                msg: "Invalid OTP!"
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "OTP Successfully Verified!"
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const resetPasswrod = async (req, res) => {
    try {
        const user = await userFunction.resetPasswrod(req);
        if (!user) {
            return res.status(200).json({
                success: false,
                msg: "No User Found To Reset Password!"
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "Password is Reset Successfully!"
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

const nearbyUsers = async (req, res) => {
    try {
        const users = await userFunction.getNearbyUsers(req);
        if (users.length === 0) {
            return res.status(200).json({
                success: false,
                msg: "No Nearby Technicians!"
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "Nearby Technicians",
                data: users
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
}

const deleteUser = async (req, res) => {
    try {
        const user = await userFunction.deleteUser(req);
        if (!user) {
            return res.status(200).json({
                success: false,
                msg: "No User Found to Delete!",
            })
        } else {
            return res.status(200).json({
                success: true,
                msg: "User is Deleted Successfully!",
            })
        }
    } catch (error) {
        console.log("Having Errors:", error);
        return res.status(403).json({
            success: false,
            msg: "Something Went Wrong!",
            error: error.message
        })
    }
};

module.exports = {
    signup,
    verifyOTP,
    login,
    userProfile,
    getAllUsers,
    updateUser,
    forgetPassword,
    verifyOTPForPassword,
    resetPasswrod,
    nearbyUsers,
    deleteUser,
    googleLogin,
    setUserType
};