const Post = require('../models/Post');
const User = require('../models/User');
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

// Helper function to compress and save image file
// Helper function to save video files
const saveVideoFile = async (file) => {
    try {
        const timestamp = Date.now();
        const randomString = Math.random().toString(36).substring(2, 15);
        const extension = path.extname(file.originalname);
        const filename = `post_video_${timestamp}_${randomString}${extension}`;
        
        const postsDir = path.join(__dirname, '..', 'uploads', 'posts');
        if (!fs.existsSync(postsDir)) {
            fs.mkdirSync(postsDir, { recursive: true });
        }
        
        const filePath = path.join(postsDir, filename);
        await fs.promises.writeFile(filePath, file.buffer);
        
        // Generate file hash for integrity
        const crypto = require('crypto');
        const fileHash = crypto.createHash('md5').update(file.buffer).digest('hex');
        
        return {
            filePath: `uploads/posts/${filename}`,
            url: `/uploads/posts/${filename}`,
            size: file.size,
            fileHash: fileHash
        };
    } catch (error) {
        console.error('Error saving video file:', error);
        throw error;
    }
};

const compressAndSaveImage = async (file, maxSizeKB = 750) => {
    try {
        console.log(`🗜️ [COMPRESSION DEBUG] Starting compression for: ${file.originalname}`);
        const originalSize = file.size;
        console.log(`🗜️ [COMPRESSION DEBUG] Original image size: ${(originalSize / 1024).toFixed(2)} KB`);
        console.log(`🗜️ [COMPRESSION DEBUG] Target size: ${maxSizeKB} KB`);
        
        // Get image metadata
        const metadata = await sharp(file.buffer).metadata();
        console.log(`🗜️ [COMPRESSION DEBUG] Original dimensions: ${metadata.width}x${metadata.height}`);
        console.log(`🗜️ [COMPRESSION DEBUG] Image format: ${metadata.format}`);
        console.log(`🗜️ [COMPRESSION DEBUG] Color space: ${metadata.space}`);
        
        let compressedBuffer = file.buffer;
        let quality = 85;
        let compressed = false;
        
        // If image is larger than max size, compress it
        while (compressedBuffer.length > maxSizeKB * 1024 && quality > 20) {
            compressed = true;
            quality -= 10;
            
            console.log(`🗜️ [COMPRESSION DEBUG] Attempting compression with quality: ${quality}`);
            
            compressedBuffer = await sharp(file.buffer)
                .jpeg({ 
                    quality: quality,
                    progressive: true,
                    mozjpeg: true
                })
                .png({ 
                    quality: quality,
                    progressive: true,
                    compressionLevel: 9
                })
                .webp({ 
                    quality: quality
                })
                .toBuffer();
                
            console.log(`🗜️ [COMPRESSION DEBUG] Compressed with quality ${quality}: ${(compressedBuffer.length / 1024).toFixed(2)} KB`);
        }
        
        // If still too large, resize the image
        if (compressedBuffer.length > maxSizeKB * 1024) {
            const scaleFactor = Math.sqrt((maxSizeKB * 1024) / compressedBuffer.length) * 0.9;
            const newWidth = Math.floor(metadata.width * scaleFactor);
            const newHeight = Math.floor(metadata.height * scaleFactor);
            
            compressedBuffer = await sharp(file.buffer)
                .resize(newWidth, newHeight, {
                    fit: 'inside',
                    withoutEnlargement: true
                })
                .jpeg({ quality: 70, progressive: true })
                .png({ quality: 70, progressive: true })
                .webp({ quality: 70 })
                .toBuffer();
                
            compressed = true;
            console.log(`📏 Resized to ${newWidth}x${newHeight}: ${(compressedBuffer.length / 1024).toFixed(2)} KB`);
        }
        
        // Generate unique filename
        const timestamp = Date.now();
        const randomString = Math.random().toString(36).substring(2, 15);
        const extension = path.extname(file.originalname);
        const filename = `post_${timestamp}_${randomString}${extension}`;
        
        console.log(`💾 [SAVE DEBUG] Generated filename: ${filename}`);
        
        // Create posts directory if it doesn't exist
        const postsDir = path.join(__dirname, '..', 'uploads', 'posts');
        console.log(`💾 [SAVE DEBUG] Posts directory: ${postsDir}`);
        
        if (!fs.existsSync(postsDir)) {
            console.log(`💾 [SAVE DEBUG] Creating posts directory...`);
            fs.mkdirSync(postsDir, { recursive: true });
        }
        
        // Save compressed file
        const filePath = path.join(postsDir, filename);
        console.log(`💾 [SAVE DEBUG] Saving file to: ${filePath}`);
        fs.writeFileSync(filePath, compressedBuffer);
        console.log(`💾 [SAVE DEBUG] File saved successfully!`);
        
        // Get final metadata
        const finalMetadata = await sharp(compressedBuffer).metadata();
        
        const result = {
            filePath: filePath,
            url: `/uploads/posts/${filename}`,
            size: compressedBuffer.length,
            width: finalMetadata.width,
            height: finalMetadata.height,
            compressed: compressed,
            originalSize: originalSize,
            filename: filename
        };
        
        console.log(`✅ [COMPRESSION DEBUG] Final result:`, {
            filename: result.filename,
            filePath: result.filePath,
            url: result.url,
            finalSize: `${(result.size / 1024).toFixed(2)} KB`,
            originalSize: `${(result.originalSize / 1024).toFixed(2)} KB`,
            compressionRatio: `${((1 - result.size / result.originalSize) * 100).toFixed(1)}%`,
            dimensions: `${result.width}x${result.height}`,
            compressed: result.compressed
        });
        
        return result;
        
    } catch (error) {
        console.error('❌ [COMPRESSION ERROR] Image compression failed:', error);
        console.error('❌ [COMPRESSION ERROR] Error details:', {
            message: error.message,
            stack: error.stack,
            file: file.originalname,
            size: file.size
        });
        throw new Error('Failed to compress and save image');
    }
};

// Helper function to validate base64 image
const validateBase64Image = (base64Data) => {
    const base64Regex = /^data:image\/(png|jpg|jpeg|gif|webp|bmp);base64,/;
    
    if (!base64Data || typeof base64Data !== 'string') {
        return { valid: false, error: 'Image data is required' };
    }
    
    if (!base64Regex.test(base64Data)) {
        return { valid: false, error: 'Invalid image format. Supported formats: PNG, JPG, JPEG, GIF, WEBP, BMP' };
    }
    
    // Check size (max 10MB before compression)
    const base64String = base64Data.includes(',') ? base64Data.split(',')[1] : base64Data;
    const sizeInBytes = (base64String.length * 3) / 4;
    const maxSize = 10 * 1024 * 1024; // 10MB
    
    if (sizeInBytes > maxSize) {
        return { valid: false, error: 'Image too large. Maximum size before compression: 10MB' };
    }
    
    return { valid: true };
};

// Create a new post
exports.createPost = async (req, res) => {
    try {
        const { 
            title, 
            description, 
            tags, 
            category, 
            visibility,
            interests // Array of interest names
        } = req.body;
        
        const authorId = req.user._id; // Assuming user is authenticated
        const files = req.files || []; // Get uploaded files

        console.log(`📝 [CREATE POST DEBUG] Post Title: "${title}"`);
        console.log(`📝 [CREATE POST DEBUG] Post Description: "${description}"`);
        console.log(`📝 [CREATE POST DEBUG] Post Tags: "${tags || ''}"`);
        console.log(`📝 [CREATE POST DEBUG] Post Category: "${category || 'general'}"`);
        console.log(`📝 [CREATE POST DEBUG] Post Visibility: "${visibility || 'public'}"`);
        console.log(`📝 [CREATE POST DEBUG] Selected Interests: ${interests}`);
        console.log(`📝 [CREATE POST DEBUG] Interests Type: ${typeof interests}`);
        console.log(`📝 [CREATE POST DEBUG] Interests Count: ${Array.isArray(interests) ? interests.length : (interests ? 1 : 0)}`);
        console.log(`📝 [CREATE POST DEBUG] Files Count: ${files.length}`);
        console.log(`📝 [CREATE POST DEBUG] Files Total Size: ${files.reduce((sum, file) => sum + file.size, 0)} characters`);
        console.log(`📝 [CREATE POST DEBUG] Post Data Keys: [${Object.keys(req.body).join(', ')}]`);
        console.log(`📝 [CREATE POST DEBUG] Author ID: ${authorId}`);
        
        // Debug file details
        if (files.length > 0) {
            console.log(`📁 [FILE DEBUG] Processing ${files.length} files:`);
            files.forEach((file, index) => {
                console.log(`📁 [FILE DEBUG] File ${index + 1}:`);
                console.log(`   - Original Name: ${file.originalname}`);
                console.log(`   - MIME Type: ${file.mimetype}`);
                console.log(`   - Size: ${(file.size / 1024).toFixed(2)} KB`);
                console.log(`   - Field Name: ${file.fieldname}`);
                console.log(`   - Buffer Length: ${file.buffer?.length || 'N/A'}`);
            });
        }

        // Validate required fields
        if (!title || !description) {
            return res.status(400).json({
                success: false,
                message: 'Title and description are required'
            });
        }

        // Check if user exists
        const user = await User.findById(authorId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Process uploaded files
        const media = [];
        if (files && files.length > 0) {
            console.log(`🖼️ [FILE PROCESSING DEBUG] Processing ${files.length} files...`);
            console.log(`🖼️ [FILE PROCESSING DEBUG] Files to process: ${files.length}`);
            
            // Limit to maximum 10 files per post
            const filesToProcess = files.slice(0, 10);
            console.log(`🖼️ [FILE PROCESSING DEBUG] Files after limit: ${filesToProcess.length}`);
            
            for (let i = 0; i < filesToProcess.length; i++) {
                const file = filesToProcess[i];
                
                console.log(`🔄 [FILE PROCESSING DEBUG] Processing file ${i + 1}/${filesToProcess.length}: ${file.originalname}`);
                console.log(`🔄 [FILE PROCESSING DEBUG] File MIME type: ${file.mimetype}`);
                console.log(`🔄 [FILE PROCESSING DEBUG] File size: ${(file.size / 1024).toFixed(2)} KB`);
                console.log(`🔄 [FILE PROCESSING DEBUG] Buffer available: ${file.buffer ? 'Yes' : 'No'}`);
                
                try {
                    // Check if it's an image (by MIME type or file extension)
                    const isImageByMime = file.mimetype.startsWith('image/');
                    const isImageByExtension = /\.(jpg|jpeg|png|gif|webp|bmp|tiff|svg)$/i.test(file.originalname);
                    const isImage = isImageByMime || isImageByExtension;
                    
                    console.log(`🖼️ [IMAGE PROCESSING DEBUG] MIME type check: ${isImageByMime}`);
                    console.log(`🖼️ [IMAGE PROCESSING DEBUG] Extension check: ${isImageByExtension}`);
                    console.log(`🖼️ [IMAGE PROCESSING DEBUG] Is image: ${isImage}`);
                    
                    if (isImage) {
                        console.log(`🖼️ [IMAGE PROCESSING DEBUG] Processing as image...`);
                        const compressionResult = await compressAndSaveImage(file);
                        
                        media.push({
                        type: 'image',
                            filePath: compressionResult.filePath,
                            url: compressionResult.url,
                            originalName: file.originalname,
                            size: compressionResult.size,
                            mimeType: file.mimetype,
                            width: compressionResult.width,
                            height: compressionResult.height,
                            compressed: compressionResult.compressed,
                            originalSize: compressionResult.originalSize,
                            filename: compressionResult.filename
                        });
                    
                    console.log(`✅ Image ${i + 1} processed:`, {
                            originalSize: `${(compressionResult.originalSize / 1024).toFixed(2)} KB`,
                            compressedSize: `${(compressionResult.size / 1024).toFixed(2)} KB`,
                            dimensions: `${compressionResult.width}x${compressionResult.height}`,
                            compressed: compressionResult.compressed
                        });
                        
                    } else if (file.mimetype.startsWith('video/')) {
                        // For videos, save without compression for now
                        const timestamp = Date.now();
                        const randomString = Math.random().toString(36).substring(2, 15);
                        const extension = path.extname(file.originalname);
                        const filename = `post_video_${timestamp}_${randomString}${extension}`;
                        
                        const postsDir = path.join(__dirname, '..', 'uploads', 'posts');
                        if (!fs.existsSync(postsDir)) {
                            fs.mkdirSync(postsDir, { recursive: true });
                        }
                        
                        const filePath = path.join(postsDir, filename);
                        fs.writeFileSync(filePath, file.buffer);
                        
                        media.push({
                            type: 'video',
                            filePath: filePath,
                            url: `/uploads/posts/${filename}`,
                            originalName: file.originalname,
                            size: file.size,
                            mimeType: file.mimetype,
                            filename: filename
                        });
                        
                        console.log(`✅ Video ${i + 1} processed:`, {
                            size: `${(file.size / 1024 / 1024).toFixed(2)} MB`,
                            filename: filename
                        });
                    } else {
                        console.log(`❌ [FILE PROCESSING DEBUG] File not processed - not recognized as image or video:`, {
                            originalName: file.originalname,
                            mimeType: file.mimetype,
                            isImageByMime: isImageByMime,
                            isImageByExtension: isImageByExtension,
                            isVideo: file.mimetype.startsWith('video/')
                        });
                    }
                    
                } catch (compressionError) {
                    console.error(`❌ File ${i + 1} processing failed:`, compressionError);
                    return res.status(400).json({
                        success: false,
                        message: `Failed to process file ${i + 1}: ${compressionError.message}`
                    });
                }
            }
        }

        // Determine post type based on media
        let postType = 'text';
        if (media.length > 0) {
            postType = media.length === 1 ? 'image' : 'image'; // Carousel for multiple images
        }
        
        console.log(`📊 [MEDIA DEBUG] Final media array:`, {
            mediaCount: media.length,
            mediaItems: media.map(item => ({
                type: item.type,
                filename: item.filename,
                url: item.url,
                size: item.size
            }))
        });

        // Process interests if provided
        let processedInterests = [];
        if (interests) {
            console.log(`🔍 [INTERESTS DEBUG] Processing interests: ${interests}`);
            console.log(`🔍 [INTERESTS DEBUG] Interests type: ${typeof interests}`);
            
            if (Array.isArray(interests)) {
                // If it's already an array
                processedInterests = interests
                    .filter(interest => interest && typeof interest === 'string' && interest.trim().length > 0)
                    .map(interest => interest.trim());
            } else if (typeof interests === 'string') {
                // If it's a string, try to parse it as JSON or split by comma
                try {
                    // Try to parse as JSON first
                    const parsedInterests = JSON.parse(interests);
                    if (Array.isArray(parsedInterests)) {
                        processedInterests = parsedInterests
                            .filter(interest => interest && typeof interest === 'string' && interest.trim().length > 0)
                            .map(interest => interest.trim());
                    }
                } catch (parseError) {
                    // If JSON parsing fails, split by comma
                    console.log(`🔍 [INTERESTS DEBUG] JSON parse failed, splitting by comma: ${parseError.message}`);
                    processedInterests = interests
                        .split(',')
                        .filter(interest => interest && interest.trim().length > 0)
                        .map(interest => interest.trim());
                }
            }
            
            console.log(`🔍 [INTERESTS DEBUG] Processed interests: [${processedInterests.join(', ')}]`);
        }

        // Create post
        const post = new Post({
            title,
            description,
            author: authorId,
            media,
            type: postType,
            tags: tags ? tags.split(',').map(tag => tag.trim().toLowerCase()) : [],
            interests: processedInterests,
            category: category || 'general',
            visibility: visibility || 'public'
        });

        await post.save();

        // Populate author information
        await post.populate('author', 'name email');

        console.log(`✅ [POST CREATION DEBUG] Post created successfully:`, {
            postId: post._id,
            title: post.title,
            mediaCount: post.media.length,
            type: post.type,
            interests: post.interests,
            category: post.category,
            visibility: post.visibility
        });

        const responseData = {
            success: true,
            message: 'Post created successfully',
            data: {
                post,
                mediaInfo: {
                    totalFiles: media.length,
                    totalSize: media.reduce((sum, file) => sum + file.size, 0),
                    compressedFiles: media.filter(file => file.compressed).length,
                    fileUrls: media.map(file => file.url)
                }
            }
        };

        console.log(`📤 [RESPONSE DEBUG] Sending response:`, {
            success: responseData.success,
            message: responseData.message,
            postId: responseData.data.post._id,
            mediaCount: responseData.data.mediaInfo.totalFiles,
            totalSize: `${(responseData.data.mediaInfo.totalSize / 1024).toFixed(2)} KB`,
            compressedFiles: responseData.data.mediaInfo.compressedFiles,
            fileUrls: responseData.data.mediaInfo.fileUrls
        });

        res.status(201).json(responseData);

    } catch (error) {
        console.error('❌ [POST CREATION ERROR] Create post failed:', error);
        console.error('❌ [POST CREATION ERROR] Error details:', {
            message: error.message,
            stack: error.stack,
            name: error.name,
            timestamp: new Date().toISOString()
        });
        
        res.status(500).json({
            success: false,
            message: 'Failed to create post',
            error: error.message,
            timestamp: new Date().toISOString()
        });
    }
};

// Get all posts with pagination and filtering
exports.getAllPosts = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const skip = (page - 1) * limit;
        
        const { category, author, tags, interests, sortBy = 'createdAt', sortOrder = 'desc' } = req.query;

        // Build filter object
        const filter = { isActive: true };
        
        if (category) filter.category = category;
        if (author) filter.author = author;
        if (tags) {
            const tagArray = tags.split(',').map(tag => tag.trim().toLowerCase());
            filter.tags = { $in: tagArray };
        }
        if (interests) {
            const interestArray = interests.split(',').map(interest => interest.trim());
            filter.interests = { $in: interestArray };
        }

        // Build sort object
        const sort = {};
        sort[sortBy] = sortOrder === 'desc' ? -1 : 1;

        const posts = await Post.find(filter)
            .populate('author', 'name email')
            .populate('likes.user', 'name')
            .populate('comments.user', 'name')
            .populate('shares.user', 'name')
            .sort(sort)
            .skip(skip)
            .limit(limit);

        const totalPosts = await Post.countDocuments(filter);
        const totalPages = Math.ceil(totalPosts / limit);

        res.json({
            success: true,
            data: {
                posts,
                pagination: {
                    currentPage: page,
                    totalPages,
                    totalPosts,
                    hasNext: page < totalPages,
                    hasPrev: page > 1
                }
            }
        });

    } catch (error) {
        console.error('Get posts error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch posts',
            error: error.message
        });
    }
};

// Get single post by ID
exports.getPostById = async (req, res) => {
    try {
        const { id } = req.params;

        const post = await Post.findById(id)
            .populate('author', 'name email')
            .populate('likes.user', 'name')
            .populate('comments.user', 'name')
            .populate('comments.replies.user', 'name')
            .populate('shares.user', 'name');

        if (!post) {
            return res.status(404).json({
                success: false,
                message: 'Post not found'
            });
        }

        // Increment view count
        await post.incrementView();

        res.json({
            success: true,
            data: post
        });

    } catch (error) {
        console.error('Get post error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch post',
            error: error.message
        });
    }
};

// Update post
exports.updatePost = async (req, res) => {
    try {
        console.log(`🔄 [UPDATE POST DEBUG] Update post request received`);
        console.log(`🔄 [UPDATE POST DEBUG] Post ID: ${req.params.id}`);
        console.log(`🔄 [UPDATE POST DEBUG] User ID: ${req.user.id}`);
        console.log(`🔄 [UPDATE POST DEBUG] Files received: ${req.files?.length || 0}`);
        console.log(`🔄 [UPDATE POST DEBUG] Body fields:`, Object.keys(req.body));

        const { id } = req.params;
        const userId = req.user.id;
        const { title, description, tags, category, visibility, interests } = req.body;

        const post = await Post.findById(id);
        if (!post) {
            return res.status(404).json({
                success: false,
                message: 'Post not found'
            });
        }

        // Check if user is the author
        if (post.author.toString() !== userId) {
            return res.status(403).json({
                success: false,
                message: 'You can only update your own posts'
            });
        }

        // Update text fields
        if (title) post.title = title;
        if (description) post.description = description;
        if (tags) post.tags = tags.split(',').map(tag => tag.trim().toLowerCase());
        if (interests !== undefined) {
            if (Array.isArray(interests)) {
                post.interests = interests
                    .filter(interest => interest && typeof interest === 'string' && interest.trim().length > 0)
                    .map(interest => interest.trim());
            } else {
                post.interests = [];
            }
        }
        if (category) post.category = category;
        if (visibility) post.visibility = visibility;

        // Handle media updates if files are provided
        if (req.files && req.files.length > 0) {
            console.log(`📁 [UPDATE POST DEBUG] Processing ${req.files.length} media files`);
            
            // Clear existing media if new media is provided
            if (post.media && post.media.length > 0) {
                console.log(`🗑️ [UPDATE POST DEBUG] Removing ${post.media.length} existing media files`);
                
                // Delete existing files from filesystem
                for (const mediaItem of post.media) {
                    if (mediaItem.filePath) {
                        try {
                            const fs = require('fs');
                            const path = require('path');
                            const fullPath = path.join(__dirname, '..', mediaItem.filePath);
                            if (fs.existsSync(fullPath)) {
                                fs.unlinkSync(fullPath);
                                console.log(`🗑️ [UPDATE POST DEBUG] Deleted file: ${mediaItem.filePath}`);
                            }
                        } catch (deleteError) {
                            console.log(`⚠️ [UPDATE POST DEBUG] Could not delete file ${mediaItem.filePath}:`, deleteError.message);
                        }
                    }
                }
            }
            
            // Process new media files
            const newMedia = [];
            let mediaCount = 0;
            
            for (const file of req.files) {
                console.log(`📁 [UPDATE POST DEBUG] Processing file: ${file.originalname} (${file.mimetype})`);
                
                try {
                    // Check if it's an image or video
                    const isImage = file.mimetype.startsWith('image/') || /\.(jpg|jpeg|png|gif|webp|bmp|tiff|svg)$/i.test(file.originalname);
                    const isVideo = file.mimetype.startsWith('video/') || /\.(mp4|avi|mov|wmv|flv|webm|mkv|3gp|ogv|m4v)$/i.test(file.originalname);
                    
                    console.log(`📁 [UPDATE POST DEBUG] Is image: ${isImage}, Is video: ${isVideo}`);
                    
                    if (isImage) {
                        // Process image with compression
                        console.log(`🖼️ [UPDATE POST DEBUG] Processing image: ${file.originalname}`);
                        const compressedImage = await compressAndSaveImage(file, 750);
                        newMedia.push({
                            type: 'image',
                            filePath: compressedImage.filePath,
                            url: compressedImage.url,
                            originalName: file.originalname,
                            size: compressedImage.size,
                            mimeType: file.mimetype,
                            width: compressedImage.width,
                            height: compressedImage.height,
                            compressed: compressedImage.compressed,
                            originalSize: compressedImage.originalSize,
                            fileHash: compressedImage.fileHash
                        });
                        mediaCount++;
                        console.log(`✅ [UPDATE POST DEBUG] Image processed: ${compressedImage.filePath}`);
                    } else if (isVideo) {
                        // Process video (save directly without compression)
                        console.log(`🎥 [UPDATE POST DEBUG] Processing video: ${file.originalname}`);
                        const videoResult = await saveVideoFile(file);
                        newMedia.push({
                            type: 'video',
                            filePath: videoResult.filePath,
                            url: videoResult.url,
                            originalName: file.originalname,
                            size: file.size,
                            mimeType: file.mimetype,
                            fileHash: videoResult.fileHash
                        });
                        mediaCount++;
                        console.log(`✅ [UPDATE POST DEBUG] Video processed: ${videoResult.filePath}`);
                    } else {
                        console.log(`⚠️ [UPDATE POST DEBUG] Skipping unsupported file type: ${file.originalname}`);
                    }
                } catch (fileError) {
                    console.error(`❌ [UPDATE POST DEBUG] Error processing file ${file.originalname}:`, fileError);
                }
            }
            
            // Update media array
            post.media = newMedia;
            console.log(`📁 [UPDATE POST DEBUG] Updated media count: ${mediaCount}`);
        }

        await post.save();

        // Populate author info for response
        await post.populate('author', 'name email');

        console.log(`✅ [UPDATE POST DEBUG] Post updated successfully`);
        res.json({
            success: true,
            message: 'Post updated successfully',
            data: post
        });

    } catch (error) {
        console.error('❌ [UPDATE POST ERROR] Update post failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update post',
            error: error.message
        });
    }
};

// Delete post
exports.deletePost = async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.id;

        const post = await Post.findById(id);
        if (!post) {
            return res.status(404).json({
                success: false,
                message: 'Post not found'
            });
        }

        // Check if user is the author
        if (post.author.toString() !== userId) {
            return res.status(403).json({
                success: false,
                message: 'You can only delete your own posts'
            });
        }

        // Delete media files
        for (const mediaItem of post.media) {
            const filePath = path.join(__dirname, '..', 'uploads', 'posts', mediaItem.filename);
            if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath);
            }
        }

        await Post.findByIdAndDelete(id);

        res.json({
            success: true,
            message: 'Post deleted successfully'
        });

    } catch (error) {
        console.error('Delete post error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete post',
            error: error.message
        });
    }
};

// Like/Unlike post
exports.toggleLike = async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.id;

        const post = await Post.findById(id);
        if (!post) {
            return res.status(404).json({
                success: false,
                message: 'Post not found'
            });
        }

        const existingLike = post.likes.find(like => like.user.toString() === userId);
        
        if (existingLike) {
            await post.removeLike(userId);
            res.json({
                success: true,
                message: 'Post unliked',
                data: { liked: false, likeCount: post.likeCount }
            });
        } else {
            await post.addLike(userId);
            res.json({
                success: true,
                message: 'Post liked',
                data: { liked: true, likeCount: post.likeCount }
            });
        }

    } catch (error) {
        console.error('Toggle like error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to toggle like',
            error: error.message
        });
    }
};

// Add comment to post
exports.addComment = async (req, res) => {
    try {
        const { id } = req.params;
        const { content } = req.body;
        const userId = req.user.id;

        if (!content) {
            return res.status(400).json({
                success: false,
                message: 'Comment content is required'
            });
        }

        const post = await Post.findById(id);
        if (!post) {
            return res.status(404).json({
                success: false,
                message: 'Post not found'
            });
        }

        await post.addComment(userId, content);
        await post.populate('comments.user', 'name');

        const newComment = post.comments[post.comments.length - 1];

        res.status(201).json({
            success: true,
            message: 'Comment added successfully',
            data: newComment
        });

    } catch (error) {
        console.error('Add comment error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add comment',
            error: error.message
        });
    }
};

// Share post
exports.sharePost = async (req, res) => {
    try {
        const { id } = req.params;
        const { platform = 'copy_link' } = req.body;
        const userId = req.user.id;

        const post = await Post.findById(id);
        if (!post) {
            return res.status(404).json({
                success: false,
                message: 'Post not found'
            });
        }

        await post.addShare(userId, platform);

        res.json({
            success: true,
            message: 'Post shared successfully',
            data: { shareCount: post.shareCount }
        });

    } catch (error) {
        console.error('Share post error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to share post',
            error: error.message
        });
    }
};

// Get user's posts
exports.getUserPosts = async (req, res) => {
    try {
        const { userId } = req.params;
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const skip = (page - 1) * limit;
        const { category, interests, sortBy = 'createdAt', sortOrder = 'desc' } = req.query;

        // Build filter object
        const filter = { 
            author: userId, 
            isActive: true 
        };

        // Add category filter if provided
        if (category) {
            filter.category = category;
        }

        // Add interests filter if provided
        if (interests) {
            const interestArray = interests.split(',').map(interest => interest.trim());
            filter.interests = { $in: interestArray };
        }

        // Build sort object - prioritize recent posts
        const sort = {};
        if (sortBy === 'createdAt') {
            sort.createdAt = sortOrder === 'desc' ? -1 : 1;
        } else if (sortBy === 'updatedAt') {
            sort.updatedAt = sortOrder === 'desc' ? -1 : 1;
        } else if (sortBy === 'likes') {
            sort['engagement.totalLikes'] = sortOrder === 'desc' ? -1 : 1;
        } else {
            sort.createdAt = -1; // Default to most recent first
        }

        const posts = await Post.find(filter)
        .populate('author', 'name email')
            .populate('likes.user', 'name')
            .populate('comments.user', 'name')
            .populate('shares.user', 'name')
            .sort(sort)
        .skip(skip)
        .limit(limit);

        const totalPosts = await Post.countDocuments(filter);
        const totalPages = Math.ceil(totalPosts / limit);

        res.json({
            success: true,
            data: {
                posts,
                pagination: {
                    currentPage: page,
                    totalPages,
                    totalPosts,
                    hasNext: page < totalPages,
                    hasPrev: page > 1
                },
                filter: {
                    category: category || null,
                    interests: interests ? interests.split(',').map(i => i.trim()) : null,
                    sortBy,
                    sortOrder
                }
            }
        });

    } catch (error) {
        console.error('Get user posts error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch user posts',
            error: error.message
        });
    }
};

// Get user's post count
exports.getUserPostCount = async (req, res) => {
    try {
        const { userId } = req.params;
        const { category, interests } = req.query;

        // Build filter object
        const filter = { 
            author: userId, 
            isActive: true 
        };

        // Add category filter if provided
        if (category) {
            filter.category = category;
        }

        // Add interests filter if provided
        if (interests) {
            const interestArray = interests.split(',').map(interest => interest.trim());
            filter.interests = { $in: interestArray };
        }

        // Get total count
        const totalPosts = await Post.countDocuments(filter);

        // Get count by category
        const categoryCounts = await Post.aggregate([
            { $match: { author: userId, isActive: true } },
            { $group: { _id: '$category', count: { $sum: 1 } } },
            { $sort: { count: -1 } }
        ]);

        // Get count by interests
        const interestCounts = await Post.aggregate([
            { $match: { author: userId, isActive: true } },
            { $unwind: '$interests' },
            { $group: { _id: '$interests', count: { $sum: 1 } } },
            { $sort: { count: -1 } },
            { $limit: 10 } // Top 10 interests
        ]);

        // Get recent activity (posts in last 30 days)
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
        
        const recentPosts = await Post.countDocuments({
            author: userId,
            isActive: true,
            createdAt: { $gte: thirtyDaysAgo }
        });

        res.json({
            success: true,
            data: {
                totalPosts,
                recentPosts,
                categoryBreakdown: categoryCounts,
                topInterests: interestCounts,
                filter: {
                    category: category || null,
                    interests: interests ? interests.split(',').map(i => i.trim()) : null
                }
            }
        });

    } catch (error) {
        console.error('Get user post count error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch user post count',
            error: error.message
        });
    }
};

// Get post statistics
exports.getPostStats = async (req, res) => {
    try {
        const stats = await Post.aggregate([
            {
                $group: {
                    _id: null,
                    totalPosts: { $sum: 1 },
                    totalLikes: { $sum: { $size: '$likes' } },
                    totalComments: { $sum: { $size: '$comments' } },
                    totalShares: { $sum: { $size: '$shares' } },
                    totalViews: { $sum: '$viewCount' },
                    avgEngagement: {
                        $avg: {
                            $add: [
                                { $size: '$likes' },
                                { $size: '$comments' },
                                { $size: '$shares' }
                            ]
                        }
                    }
                }
            }
        ]);

        const categoryStats = await Post.aggregate([
            {
                $group: {
                    _id: '$category',
                    count: { $sum: 1 }
                }
            }
        ]);

        res.json({
            success: true,
            data: {
                overall: stats[0] || {
                    totalPosts: 0,
                    totalLikes: 0,
                    totalComments: 0,
                    totalShares: 0,
                    totalViews: 0,
                    avgEngagement: 0
                },
                byCategory: categoryStats
            }
        });

    } catch (error) {
        console.error('Get post stats error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch post statistics',
            error: error.message
        });
    }
};

// Get posts by interests
exports.getPostsByInterests = async (req, res) => {
    try {
        const { interests } = req.params;
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const skip = (page - 1) * limit;

        if (!interests) {
            return res.status(400).json({
                success: false,
                message: 'Interests parameter is required'
            });
        }

        // Split interests by comma and trim whitespace
        const interestArray = interests.split(',').map(interest => interest.trim());

        const filter = { 
            isActive: true,
            interests: { $in: interestArray }
        };

        const posts = await Post.find(filter)
            .populate('author', 'name email')
            .populate('likes.user', 'name')
            .populate('comments.user', 'name')
            .sort({ createdAt: -1 })
            .skip(skip)
            .limit(limit);

        const totalPosts = await Post.countDocuments(filter);
        const totalPages = Math.ceil(totalPosts / limit);

        res.json({
            success: true,
            data: posts,
            pagination: {
                currentPage: page,
                totalPages: totalPages,
                totalItems: totalPosts,
                itemsPerPage: limit
            },
            filter: {
                interests: interestArray
            }
        });

    } catch (error) {
        console.error('Get posts by interests error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch posts by interests',
            error: error.message
        });
    }
};
