const userModel = require("../models/user");
const bcrypt = require("bcrypt");

const signup = async (decode) => {
    const { password } = decode;
    console.log("SignUp Token :", decode);
    // return
    const newUser = new userModel(decode);
    const hash = await bcrypt.hash(password, 10);
    newUser.password = hash;
    const result = await newUser.save(); 
    console.log("result :", result);
    return result
};

const getUser = async (req) => {
    let { email } = req.body;
    email = email?.toLowerCase();
    const user = await userModel.findOne({ email: email });
    return user;
};

const getUserById = async (req) => {
    const { userId } = req.query;
    const user = await userModel.findById(userId).select("-password").populate("service");
      if(user.type === "User"){
        const data = user.toObject();
        delete data.avgRating,
        delete data.workingHours,
        delete data.favouriteBy,
        delete data.service,
        delete data.portfolio,
        delete data.totalReviews
        return data
    } else {
        return user;
    }
};

const getUserData = async (req) => {
    const { userId } = req.body;
    console.log("Function :", userId);
    const user = await userModel.findById(userId).select("-password");
    if(user.type === "User"){
        const data = user.toObject();
        delete data.avgRating,
        delete data.workingHours,
        delete data.favouriteBy,
        delete data.service,
        delete data.portfolio,
        delete data.totalReviews
        return data
    } else {
        return user;
    }
};

const getAllUsers = async (req) => {
    const { type } = req.query;

    const filter = {};

    if(type){
        filter.type = type
    }

    const users = await userModel.find(filter).select("-password");
    
    return users
};

const updateUser = async (req) => {
    const { userId } = req.body;
    const updatedData = req.body;
    
    if(req.files.profileImage && req.files.profileImage[0].filename){
        updatedData.profileImage = req.files.profileImage[0].filename
    };

    if(req.files.portfolio && req.files.portfolio[0].filename){
        updatedData.portfolio = req.files.portfolio.map(file => file.filename);
    };

    if(req.files.license && req.files.license[0].filename){
        updatedData.pestControlLicense = req.files.license.map(file => file.filename);
    }

    if(req.body.workingHours){
        updatedData.workingHours = JSON.parse(req.body.workingHours);
    };

    if(req.body.longitude && req.body.latitude){
        updatedData.location = {
            type: "Point",
            coordinates: [parseFloat(req.body.longitude), parseFloat(req.body.latitude)],
            locationName: req.body.locationName || null
        }
    };

    const user = await userModel.findByIdAndUpdate(userId, 
        { $set: updatedData },
        { new: true }
    ).select("-password");
    if(user.type === "User"){
        const data = user.toObject();
        delete data.avgRating,
        delete data.workingHours,
        delete data.favouriteBy,
        delete data.service,
        delete data.portfolio,
        delete data.totalReviews
        return data    
    } else {
        return user
    }
};

const resetPasswrod = async (req) => {
    const {userId, password} = req.body;
    const hash = await bcrypt.hash(password, 10);
    const user = await userModel.findByIdAndUpdate(userId, 
        { $set: {password: hash } },
        { new: true }
    );
    return user
};

const getNearbyUsers = async (req) => {
    const { service, longitude, latitude } = req.query;
    const location = {
        type: "Point",
        coordinates: [ parseFloat(longitude), parseFloat(latitude) ],
    };

    const users = await userModel.find({
        type: "Technician",
        service,
        location:{
            $near:{
                $geometry: {
                    type: "Point",
                    coordinates: location.coordinates
                },
                $maxDistance: 100000
            }
        }
    }).select("-password").populate("service");
    return users
};

const deleteUser = async (req) => {
    const { userId } = req.query;
    const user = await userModel.findByIdAndUpdate(userId,
        { $set: { fullName: null, profileImage: null, isDeleted: true}}
    );
    return user
};

const updatedRatings = async (data) => {
    const { technicianId, avgRating, totalReviews } = data;
    const user = await userModel.findByIdAndUpdate({_id: technicianId},
        { $set: { avgRating: avgRating, totalReviews: totalReviews}},
        { new: true }
    );
    return user
};

const mapPortfolioAndLicense = async (req) => {
    
    const imagePaths = {};

    if(req.files.profileImage && req.files.profileImage[0].filename){
        imagePaths.profileImage = req.files.profileImage[0].filename
    };
    
    if(req.files.portfolio && req.files.portfolio[0].filename){
        imagePaths.portfolio = req.files.portfolio.map(file => file.filename);
    };
    
    if(req.files && req.files[0].filename){
        imagePaths.pestControlLicense = req.files.map(file => file.filename);
    };
    console.log("Function :", imagePaths)
    return imagePaths
};

module.exports = {
    signup,
    mapPortfolioAndLicense,
    getUser,
    getUserById,
    getUserData,
    getAllUsers,
    updateUser,
    resetPasswrod,
    getNearbyUsers,
    deleteUser,
    updatedRatings
};