const postingModel = require("../models/postingModel");
const { addPostAuth } = require("../authentication/postAuth");
const { uploadPostImage } = require("../helper/postImage");
const fs = require("fs").promises;

const addPost = async (req, res, next) => {
  try {
    let { title, description, userName, date } = req.body;
    let postImage = "";

    await addPostAuth(title, description, userName, date);

    if (req.files && req.files.photo) {
      const photo = req.files.photo;
      const path = await uploadPostImage(photo,req);
      postImage = path;
      console.log("Image path: ", postImage);
    }

    const post = await postingModel.create({
      title,
      postImage,
      description,
      userName,
      date,
    });

    res.status(200).json({ message: "Post Added Successfully", post });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const getPostById = async (req, res) => {
  const { id } = req.params;

  try {
    const singlePost = await postingModel.findById(id);
    if (!singlePost) {
      return res.status(404).json({ error: "No Such Post Found" });
    }
    return res.status(200).json(singlePost);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const getAllPost = async (req, res) => {
  try {
    const allPost = await postingModel.find({}).sort({ createdAt: -1 });
    res.status(200).json(allPost);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const updatePost = async (req, res) => {
  const { id } = req.params;

  try {
    const postCheck = await postingModel.findById(id);
    if (!postCheck) {
      return res.status(400).json({ error: "No Such Post Found" });
    }

    const change = {
      description: req.body.description,
      userName: req.body.userName,
      date: req.body.date,
      postImage: postCheck.postImage,
    };

    if (req.files && req.files.photo) {
      if (postCheck.postImage) {
        await fs.unlink(`${process.env.POST_IMAGE_PATH}/${postCheck.postImage}`);
      }
      const image = req.files.photo;
      const path = await uploadPostImage(image);
      change.postImage = path;
    }

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

    return res.status(200).json({ message: "Post Updated Successfully", post });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const postDelete = async (req, res) => {
  const { id } = req.params;

  try {
    const post = await postingModel.findOneAndDelete({ _id: id });
    if (!post) {
      return res.status(404).json({ error: "No Such Post Found" });
    }
    if (post.postImage) {
      await fs.unlink(`${process.env.POST_IMAGE_PATH}/${post.postImage}`);
    }
    return res.status(200).json({ message: "Post Deleted Successfully" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

module.exports = {
  addPost,
  getPostById,
  getAllPost,
  updatePost,
  postDelete,
};
