const CafePost = require('../models/CafePost'); // Import the model

// Create a new post
const path = require('path'); // Import path module to handle file paths

exports.createPost = async (req, res) => {
    try {
        const { postMessage } = req.body;

        // Extract the image name only (e.g., "1741789830223-icon192.png")
        const image_url = req.file ? path.basename(req.file.path) : null;

        // Create a new post with the image name
        const post = new CafePost({ postMessage, image_url });

        await post.save();
        res.status(201).json(post);
    } catch (error) {
        console.error('Error creating post:', error);
        res.status(500).json({ error: 'Error creating post' });
    }
};

// Get all posts
exports.getPosts = async (req, res) => {
    try {
        const posts = await CafePost.find().sort({createdAt:-1});
        res.status(200).json(posts);
    } catch (error) {
        res.status(500).json({ error: 'Error fetching posts' });
    }
};

// Get a single post by ID
exports.getPostById = async (req, res) => {
    try {
        const post = await CafePost.findById(req.params.id);
        if (!post) return res.status(404).json({ error: 'Post not found' });
        res.status(200).json(post);
    } catch (error) {
        res.status(500).json({ error: 'Error fetching post' });
    }
};

// Update a post by ID
exports.updatePost = async (req, res) => {
    try {
        const { postMessage, status } = req.body;
        const image_url = req.file ? req.file.path : undefined; // If a new image is uploaded
        const post = await CafePost.findByIdAndUpdate(
            req.params.id,
            { postMessage, status, ...(image_url && { image_url }) },
            { new: true } // Return the updated post
        );
        if (!post) return res.status(404).json({ error: 'Post not found' });
        res.status(200).json(post);
    } catch (error) {
        res.status(500).json({ error: 'Error updating post' });
    }
};

// Delete a post by ID
exports.deletePost = async (req, res) => {
    try {
        const post = await CafePost.findByIdAndDelete(req.params.id);
        if (!post) return res.status(404).json({ error: 'Post not found' });
        res.status(200).json({ message: 'Post deleted successfully' });
    } catch (error) {
        res.status(500).json({ error: 'Error deleting post' });
    }
};
