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

const signup = async (decode) => {
    const { email, password, phone, DOB} = decode;
    const hash = await bcrypt.hash(password, 10);
    const newUser = new userModel({
        email,
        phone,
        password: hash,
        DOB
    });
    const result = await newUser.save();
    return result;
};

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

const getProfile = async (userId) => {
    const user = await userModel.findById({_id: userId}).select("-password"); 
    return user
};

const updateUser = async (req) => {
    const updatedData = req.body;
    const { userId } = req.body;
    if( req.file && req.file.filename){
        updatedData.profileImage = req.file.filename;
        console.log("ImagePath :", updatedData.profileImage);
    }
    const user = await userModel.findByIdAndUpdate({_id: userId},
        {$set: { ...updatedData, profileCreted: true }},
        { new: true }
    ).select("-password");
    return user;
};

const updatePassword = async (req) =>{
    const { userId, password } = req.body

    const hash = await bcrypt.hash(password, 10);
    const update = await userModel.findByIdAndUpdate({_id: userId},
        { $set: { password: hash}},
        { new: true }
    );
    return update 
};

const addUserLocation = async (locationData) => {
    console.log("first :", locationData.location)
    const { userId, location } = locationData;
        const longitude = locationData.location.coordinates[0];
        const latitude = locationData.location.coordinates[1];
    // console.log("locationData :", longitude);
    // return 
    const newLocation = {
        type: "Point",
        coordinates: [ parseFloat(longitude), parseFloat(latitude) ],
        locationName:  location.locationName || null,
        title: location.title || null 
    };    

    console.log("Location Object :", location);
    const user = await userModel.findByIdAndUpdate(userId,
        { $set: {location: newLocation, latitude: latitude, longitude: longitude}},
        { new: true }
    ).select("-password");
    
    return user;
};

const addLocation = async (req) => {
    const { userId, latitude, longitude, locationName, title } = req.body;
    const location = {
        type: "Point",
        coordinates: [ parseFloat(longitude), parseFloat(latitude) ],
        locationName: locationName || null,
        title: title || null
    };
    const newLocation = new locationModel({
        userId,
        location
    });
    const result = await newLocation.save();
    return result
};


const editLocation = async (req) => {
    const { locationId, longitude, latitude,locationName, title } = req.body;
    
    const updatedFields = {};
     if(longitude && latitude){
        updatedFields["location.coordinates"] = [ parseFloat(longitude), parseFloat(latitude) ] 
     };
     
     if(locationName){
        updatedFields["location.locationName"] = locationName
     };

     if(title){
        updatedFields["location.title"] = title
     }
    const location = await locationModel.findByIdAndUpdate(locationId, 
        { $set: updatedFields },
        { new: true }
    );
    return location;

};

const getAllLocations = async (req) => {
    const { userId } = req.query;
    const location = await locationModel.find({userId: userId});
    return location
};

const selectLocation = async (req) => {
    const { userId, locationId } = req.query;
    const location = await locationModel.findByIdAndUpdate({_id: locationId},
        { $set: { "location.isSelected": true }},
        { new: true }
    );
    const locations = await locationModel.updateMany({userId: userId},
        { $set: {"location.isSelected": false}},
        { new: true }
    );

    return location
};

const deleteLocation = async (req) => {
    const { locationId } = req.query;
    const location = await locationModel.findByIdAndDelete({_id: locationId});
    return location 
};

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

const getAllUsers = async (req) => {
    const users = await userModel.find().select("-password");
    return users;
};

module.exports = {
    signup,
    getUser,
    getProfile,
    updateUser,
    updatePassword,
    addLocation,
    addUserLocation,
    editLocation,
    getAllLocations,
    selectLocation,
    deleteLocation,
    deleteUser,
    getAllUsers
};