const User = require("../models/user");
const { signin, signup, createToken } = require("../authentication/userAuth");
const fs = require("fs");
const { uploadsImage } = require("../helper/testt");
const user = require("../models/user");
const { reset } = require("../helper/passwordReset");
const {TextDecoder, TextEncoder} = require("util");
////////////////
///.............................................
const userSignup = async (req, res) => {
  try {
    let { email, password,  userName, coordinate } = req.body;
    // userImage = "";
    const hash = await signup(email, password, userName, coordinate);
    if (req.files) {
      let image = req.files.photo;
      const path = await uploadsImage(image,req);
      userImage = path;
    }
    // const userToken = createToken(user._id);
    await User.create({
      email,
      password: hash,
      userImage,
      userName,
      coordinate,
    });
    res.status(200).json({ message: "Registration Successfull" });
  } catch (error) {
    return res.status(404).json({ error: error.message });
    // console.log(error);
  }
};

////user login ..................
const userSignin = async (req, res, next) => {
  const { email, password } = req.body;
  try {
    const user = await signin(email, password);

    //create token
    const token = createToken(user._id);
    res.status(200).json({ message: "Login Successfully", user, token });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// get all user..........................
const getAllUser = async (req, res) => {
  const allUser = await User.find({}).sort({ createdAt: -1 });
  console.log(allUser)
  res.status(200).json(allUser);
};

//get a single user by id,,,,,,,,,,,,,,,,,,,,,,,,
const getById = async (req, res) => {
  const { id } = req.params;
  // if (!Mongoose.Types.ObjectId.isValid(id)) {
  //   return res.status(404).json({ error: "no such user found" });
  // }
  const user = await User.findById(id);

  if (!user) {
    return res.status(404).json({ error: "no such user found" });
  }
  return res.status(200).json(user);
};

//delete user by Id
const userDelete = async (req, res) => {
  const { id } = req.params;

  const user = await User.findOneAndDelete({ _id: id });
  if (!user) {
    return res.status(404).json({ error: "no such user found" });
  }
  if (req.files) {
    fs.unlink(`${process.env.FILE_UPLOAD_PATH}/${user.userImage}`, (err) => {
      if (err) {
        console.error(err);
        return;
      }
    });
  }
  return res.status(200).json({ message: "Delete Successfully" });
};

//update user ........................
const updateUser = async (req, res) => {
  const { id } = req.params;

  try {
    const userCheck = await User.findById(id);
    let image = req.files ? req.files.photo : userCheck.userImage;
    if (!userCheck) {
      return res.status(400).json({ error: "no such user found" });
    }
    const change = {
      userName: req.body.userName,
      email: req.body.email,
      password: req.body.password,
      coordinate: req.body.coordinate,
      userImage: userCheck.userImage,
    };
    if (req.files) {
      
      if (userCheck.userImage) {
        fs.unlink(
          `${process.env.FILE_UPLOAD_PATH}/${userCheck.userImage}`,
          (err) => {
            if (err) {
              console.error(err);
              return;
            }
          }
        );
      }
      let image = req.files.photo;
      const path = await uploadsImage(image,req);

      change.userImage = path;
    }
    const post = await User.findByIdAndUpdate(id, change, {
      new: true,
    });

    return res.status(200).json({ message: "Update Successfull", post });
  } catch (error) {
    res.status(404).json(error);
    // console.log(error);
  }
};

const passwordReset = async (req, res) => {
  try {
    const { email, password } = req.body;

    const resetpassword = await reset(email, password);

    res.status(200).json({ message: "Password Reset Successfull" });
  } catch (error) {
    return res.status(404).json({ error: error.message });
    // console.log(error);
  }
};
const addFriend = async (req, res) => {
  try {
    const { id, friend_id } = req.body;

    // Check if the friend_id exists in the database
    const friendUser = await User.findById(friend_id);
    if (!friendUser) {
      return res.status(404).json({ error: "Friend user not found" });
    }

    // Check if the user's ID is already in the friend's friends_list
    const isRequestSent = friendUser.friends_list.some(
      (friend) => friend.friend_id === id
    );

    if (isRequestSent) {
      return res.status(400).json({ message: "Friend request already sent or you are Already friend" });
    }

    // Add the user's id to the friend's friends_list
    friendUser.friends_list.push({ friend_id: id });
    await friendUser.save();

    return res.status(200).json({ message: "Friend request sent!" });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};



const acceptFriendRequest = async (req, res) => {
  try {
    const { id, friend_id } = req.body;

    // Find the current user
    const currentUser = await User.findById(id);
    if (!currentUser) {
      return res.status(404).json({ error: "User not found" });
    }

    // Find the friend in the user's friends_list
    const friendIndex = currentUser.friends_list.findIndex(
      (friend) => friend.friend_id === friend_id
    );

    if (friendIndex === -1) {
      return res.status(404).json({ error: "Friend not found in the user's list" });
    }

    // Update the request_accepted to true for the friend
    currentUser.friends_list[friendIndex].request_accepted = true;
    await currentUser.save();

    // Find the friend user and update request_accepted to true for the user in their friends_list
    const friendUser = await User.findById(friend_id);
    if (!friendUser) {
      return res.status(404).json({ error: "Friend user not found" });
    }

    const userIndex = friendUser.friends_list.findIndex(
      (friend) => friend.friend_id === id
    );

    if (userIndex !== -1) {
      friendUser.friends_list[userIndex].request_accepted = true;
      await friendUser.save();
    } else {
      // Add the user as a friend in the friend's friends_list and set request_accepted to true
      friendUser.friends_list.push({ friend_id: id, request_accepted: true });
      await friendUser.save();
    }

    return res.status(200).json({ message: "Friend request accepted!" });
  } catch (error) {
    return res.status(500).json({ error: error.message });
  }
};






module.exports = {
  userSignup,
  userSignin,
  userDelete,
  getById,
  getAllUser,
  updateUser,
  passwordReset,
  addFriend,
acceptFriendRequest
};
