const Post = require('../models/post');
const User = require('../models/user');

exports.createPost = async (req, res) => {
    try {
    if (!req.file) {
      return res.status(400).json({ message: "Image file is required." });
    }

    // 1. Grab any text fields you sent in the body
    //    (e.g. title, content, tags—whatever your schema expects)
    const { title, content } = req.body;

    // 2. Ensure the upload succeeded

    // 3. Build a URL/path for where the image lives
    //    Using the same path logic as in your multer storage
    //    E.g. if you serve /uploads as static:
    //      app.use("/uploads", express.static(path.join(__dirname, "../uploads")));
    const imageUrl = `/uploads/posts/${req.file.filename}`;

    // 4. Grab the authenticated user ID that your authMiddleware set
    const userId = req.user.userId || req.user.id || req.user._id;
    if (!userId) {
      return res
        .status(401)
        .json({ message: "User not authenticated." });
    }

    // 5. Create and save the post document
    const newPost = new Post({
      user_id: userId,
      content,
      image: imageUrl,
    });
    await newPost.save();

    // 6. Return the newly created post
    return res.status(201).json(newPost);
  } catch (err) {
    console.error("Error in createPost:", err);
    return res.status(500).json({
      message: "Server error creating post",
      error: err.message,
    });
  }
};

exports.getPosts = async (req, res) => {
  try {
    // 1) Get userId from req.user (set by authMiddleware)
    const userId = req.user.userId || req.user.id || req.user._id;
    if (!userId) {
      return res.status(401).json({ message: "User not authenticated." });
    }

    const user = await User.findById(userId).select("username");

    console.log("Fetching posts for user ID:", userId);
    // 2) Fetch that user's posts, populate author info, sort newest first
    const posts = await Post.find({ user_id: userId }).sort({ timestamp: -1 })

    console.log("Retrieved posts:", posts);

    if (!posts || posts.length === 0) {
      return res.status(404).json({ message: "No posts found." });
    }

    // 3) Build full URL for each image
    const host = req.get("host");
    const protocol = req.protocol;
    const postsWithFullUrl = posts.map(post => {
      // post.image is something like "/uploads/posts/<filename>"
      const fullImageUrl = `${protocol}://${host}${post.image}`;

      return {
        _id:       post._id,
        content:   post.content,
        image:     fullImageUrl,
        createdAt: post.timestamp,
        username: user,
      };
    });

    // 4) Send back the array
    return res.status(200).json(postsWithFullUrl);

  } catch (error) {
    console.error("Error retrieving posts:", error);
    return res.status(500).json({
      message: "Server error while retrieving posts",
      error:   error.message,
    });
  }
};

exports.getLatestPosts = async (req, res) => {
    try {
        // 1) Get the latest 10 posts, sorted by createdAt descending
        const posts = await Post.find()
        .sort({ timestamp: -1 })
        .limit(10)
        .populate("user_id", "username")
    
        if (!posts || posts.length === 0) {
        return res.status(404).json({ message: "No posts found." });
        }

        console.log("Retrieved latest posts:", posts);
    
        // 2) Build full URL for each image
        const host = req.get("host");
        const protocol = req.protocol;
        const postsWithFullUrl = posts.map(post => {
        const fullImageUrl = `${protocol}://${host}${post.image}`;
            
        return {
            content:   post.content,
            image:     fullImageUrl,
            createdAt: post.timestamp,
            username: post.user_id.username,
            profile_pic: post.user_id.profile_pic,
        };
        });
    
        // 3) Send back the array
        return res.status(200).json(postsWithFullUrl);
    
    } catch (error) {
        console.error("Error retrieving latest posts:", error);
        return res.status(500).json({
        message: "Server error while retrieving latest posts",
        error:   error.message,
        });
    }
    }