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

// Helper function to save video file
const saveVideoFile = async (file, maxSizeMB = 100) => {
    console.log(`🎬 [VIDEO SAVE DEBUG] Processing video file: ${file.originalname}`);
    console.log(`🎬 [VIDEO SAVE DEBUG] File size: ${(file.size / 1024 / 1024).toFixed(2)}MB`);
    console.log(`🎬 [VIDEO SAVE DEBUG] File MIME type: ${file.mimetype}`);
    
    try {
        // Generate unique filename
        const timestamp = Date.now();
        const randomString = Math.random().toString(36).substring(2, 15);
        const fileExtension = path.extname(file.originalname);
        const fileName = `cut_${timestamp}_${randomString}${fileExtension}`;
        const filePath = path.join(__dirname, '..', 'uploads', 'cuts', fileName);
        
        console.log(`🎬 [VIDEO SAVE DEBUG] Generated filename: ${fileName}`);
        console.log(`🎬 [VIDEO SAVE DEBUG] Full file path: ${filePath}`);
        
        // Ensure directory exists
        const uploadDir = path.dirname(filePath);
        console.log(`🎬 [VIDEO SAVE DEBUG] Upload directory: ${uploadDir}`);
        
        if (!fs.existsSync(uploadDir)) {
            console.log(`🎬 [VIDEO SAVE DEBUG] Creating cuts directory: ${uploadDir}`);
            fs.mkdirSync(uploadDir, { recursive: true });
            console.log(`✅ [VIDEO SAVE DEBUG] Cuts directory created successfully`);
        } else {
            console.log(`✅ [VIDEO SAVE DEBUG] Cuts directory already exists`);
        }
        
        // Save file
        console.log(`🎬 [VIDEO SAVE DEBUG] Writing video file to disk...`);
        fs.writeFileSync(filePath, file.buffer);
        console.log(`✅ [VIDEO SAVE DEBUG] Video file written to disk successfully`);
        
        // Get file stats
        const stats = fs.statSync(filePath);
        const fileSizeMB = stats.size / (1024 * 1024);
        
        console.log(`🎬 [VIDEO SAVE DEBUG] Video saved: ${fileName}`);
        console.log(`🎬 [VIDEO SAVE DEBUG] File size on disk: ${fileSizeMB.toFixed(2)}MB`);
        console.log(`🎬 [VIDEO SAVE DEBUG] File path on disk: ${filePath}`);
        
        // Generate file hash
        const crypto = require('crypto');
        const fileHash = crypto.createHash('md5').update(file.buffer).digest('hex');
        console.log(`🎬 [VIDEO SAVE DEBUG] File hash: ${fileHash}`);
        
        const result = {
            fileName,
            filePath,
            url: `/uploads/cuts/${fileName}`,
            originalName: file.originalname,
            size: stats.size,
            mimeType: file.mimetype,
            fileHash
        };
        
        console.log(`🎬 [VIDEO SAVE DEBUG] Video save result:`, result);
        
        return result;
        
    } catch (error) {
        console.error(`❌ [VIDEO SAVE ERROR] Failed to save video:`, error);
        throw error;
    }
};

// Helper function to generate video thumbnail
const generateThumbnail = async (videoPath, outputPath) => {
    try {
        console.log(`🎬 [THUMBNAIL DEBUG] Generating thumbnail for: ${videoPath}`);
        
        const ffmpeg = require('fluent-ffmpeg');
        const thumbnailPath = outputPath.replace(/\.[^/.]+$/, '_thumb.jpg');
        
        // Ensure thumbnails directory exists - create separate thumbnails folder
        const cutsDir = path.join(__dirname, '..', 'uploads', 'cuts');
        const thumbnailsDir = path.join(cutsDir, 'thumbnails');
        if (!fs.existsSync(thumbnailsDir)) {
            fs.mkdirSync(thumbnailsDir, { recursive: true });
            console.log(`🎬 [THUMBNAIL DEBUG] Created thumbnails directory: ${thumbnailsDir}`);
        }
        
        // Update thumbnail path to use thumbnails subdirectory
        const thumbnailFileName = path.basename(thumbnailPath);
        const finalThumbnailPath = path.join(thumbnailsDir, thumbnailFileName);
        
        return new Promise((resolve, reject) => {
            ffmpeg(videoPath)
                .screenshots({
                    timestamps: ['10%'], // Extract frame at 10% of video duration
                    filename: thumbnailFileName,
                    folder: thumbnailsDir,
                    size: '320x240' // Standard thumbnail size
                })
                .on('end', () => {
                    console.log(`✅ [THUMBNAIL DEBUG] Thumbnail generated successfully: ${thumbnailPath}`);
                    resolve(`/uploads/cuts/thumbnails/${path.basename(thumbnailPath)}`);
                })
                .on('error', (error) => {
                    console.error(`❌ [THUMBNAIL ERROR] FFmpeg error:`, error);
                    
                    // Fallback: Create a simple placeholder thumbnail
                    console.log(`🎬 [THUMBNAIL DEBUG] FFmpeg not available, creating fallback thumbnail...`);
                    console.log(`🎬 [THUMBNAIL DEBUG] To enable video frame extraction, install FFmpeg: https://ffmpeg.org/download.html`);
                    
                    sharp({
                        create: {
                            width: 320,
                            height: 240,
                            channels: 3,
                            background: { r: 30, g: 30, b: 30 } // Dark background
                        }
                    })
                    .composite([{
                        input: Buffer.from(`
                            <svg width="320" height="240">
                                <rect width="320" height="240" fill="#1e1e1e"/>
                                <text x="160" y="100" font-family="Arial" font-size="16" fill="#ffffff" text-anchor="middle">Video Thumbnail</text>
                                <text x="160" y="130" font-family="Arial" font-size="12" fill="#cccccc" text-anchor="middle">Install FFmpeg for auto-generation</text>
                            </svg>
                        `),
                        top: 0,
                        left: 0
                    }])
                    .jpeg({ quality: 80 })
                    .toFile(finalThumbnailPath)
                    .then(() => {
                        console.log(`✅ [THUMBNAIL DEBUG] Fallback thumbnail created: ${finalThumbnailPath}`);
                        resolve(`/uploads/cuts/thumbnails/${thumbnailFileName}`);
                    })
                    .catch(fallbackError => {
                        console.error(`❌ [THUMBNAIL ERROR] Fallback thumbnail failed:`, fallbackError);
                        reject(fallbackError);
                    });
                });
        });
        
    } catch (error) {
        console.error(`❌ [THUMBNAIL ERROR] Failed to generate thumbnail:`, error);
        return null;
    }
};

// Create a new cut
exports.createCut = async (req, res) => {
    try {
        const { title, description, visibility, interests, tags, user_id } = req.body;
        // Use user_id from request body if provided, otherwise use authenticated user
        const userId = user_id || req.user._id;
        
        console.log(`🎬 [CREATE CUT DEBUG] Creating cut for user: ${userId}`);
        console.log(`🎬 [CREATE CUT DEBUG] User ID from body: ${user_id}`);
        console.log(`🎬 [CREATE CUT DEBUG] Authenticated user: ${req.user._id}`);
        console.log(`🎬 [CREATE CUT DEBUG] Final user ID: ${userId}`);
        console.log(`🎬 [CREATE CUT DEBUG] Cut title: "${title}"`);
        console.log(`🎬 [CREATE CUT DEBUG] Cut description: "${description}"`);
        console.log(`🎬 [CREATE CUT DEBUG] Cut visibility: "${visibility}"`);
        console.log(`🎬 [CREATE CUT DEBUG] Cut interests:`, interests);
        console.log(`🎬 [CREATE CUT DEBUG] Cut tags:`, tags);
        
        // Check if video file is provided
        if (!req.file) {
            console.log(`❌ [CREATE CUT DEBUG] No video file provided`);
            return res.status(400).json({
                success: false,
                message: 'Video file is required'
            });
        }
        
        console.log(`🎬 [CREATE CUT DEBUG] Video file: ${req.file.originalname} (${req.file.mimetype})`);
        
        // Save video file
        const videoData = await saveVideoFile(req.file);
        console.log(`🎬 [CREATE CUT DEBUG] Video saved successfully`);
        
        // Generate thumbnail
        const thumbnail = await generateThumbnail(videoData.filePath, videoData.filePath);
        console.log(`🎬 [CREATE CUT DEBUG] Thumbnail: ${thumbnail}`);
        
        // Parse interests if it's a string
        let parsedInterests = interests;
        if (typeof interests === 'string') {
            try {
                parsedInterests = JSON.parse(interests);
            } catch (e) {
                parsedInterests = interests.split(',').map(i => i.trim());
            }
        }
        
        // Parse tags if it's a string
        let parsedTags = tags;
        if (typeof tags === 'string') {
            try {
                parsedTags = JSON.parse(tags);
            } catch (e) {
                parsedTags = tags.split(',').map(t => t.trim());
            }
        }
        
        // Create cut
        const cut = new Cuts({
            title,
            description,
            visibility: visibility || 'public',
            interests: parsedInterests || [],
            tags: parsedTags || [],
            video: {
                ...videoData,
                thumbnail: thumbnail
            },
            user_id: userId
        });
        
        await cut.save();
        
        // Populate user details
        await cut.populate('user_id', 'name mobile profileImage');
        
        console.log(`✅ [CREATE CUT DEBUG] Cut created successfully: ${cut._id}`);
        
        res.status(201).json({
            success: true,
            message: 'Cut created successfully',
            data: {
                cut: {
                    _id: cut._id,
                    title: cut.title,
                    description: cut.description,
                    visibility: cut.visibility,
                    interests: cut.interests,
                    tags: cut.tags,
                    video: {
                        fileName: cut.video.fileName,
                        url: cut.video.url,
                        originalName: cut.video.originalName,
                        size: cut.video.size,
                        mimeType: cut.video.mimeType,
                        thumbnail: cut.video.thumbnail
                    },
                    user_id: cut.user_id,
                    author: {
                        _id: cut.user_id._id,
                        name: cut.user_id.name,
                        mobile: cut.user_id.mobile,
                        profileImage: cut.user_id.profileImage
                    },
                    engagement: cut.engagement,
                    views: cut.views,
                    isActive: cut.isActive,
                    createdAt: cut.createdAt
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [CREATE CUT ERROR] Create cut failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to create cut',
            error: error.message
        });
    }
};

// Get all cuts with pagination and filtering
exports.getAllCuts = async (req, res) => {
    try {
        const { 
            page = 1, 
            limit = 10, 
            visibility = 'public', 
            interests, 
            tags,
            sortBy = 'createdAt',
            sortOrder = 'desc'
        } = req.query;
        
        console.log(`🎬 [GET CUTS DEBUG] Getting all cuts with filters:`, {
            page, limit, visibility, interests, tags, sortBy, sortOrder
        });
        
        const skip = (page - 1) * limit;
        let query = { isActive: true };
        
        // Apply visibility filter
        if (visibility && visibility !== 'all') {
            query.visibility = visibility;
        }
        
        // Apply interests filter
        if (interests) {
            const interestsArray = interests.split(',').map(i => i.trim());
            query.interests = { $in: interestsArray };
        }
        
        // Apply tags filter
        if (tags) {
            const tagsArray = tags.split(',').map(t => t.trim());
            query.tags = { $in: tagsArray };
        }
        
        // Build sort object
        const sort = {};
        sort[sortBy] = sortOrder === 'desc' ? -1 : 1;
        
        const cuts = await Cuts.find(query)
            .populate('user_id', 'name mobile profileImage')
            .sort(sort)
            .skip(skip)
            .limit(parseInt(limit));
        
        const total = await Cuts.countDocuments(query);
        
        console.log(`📊 [GET CUTS DEBUG] Found ${cuts.length} cuts out of ${total} total`);
        
        res.json({
            success: true,
            message: 'Cuts retrieved successfully',
            data: {
                cuts,
                pagination: {
                    currentPage: parseInt(page),
                    totalPages: Math.ceil(total / limit),
                    totalCuts: total,
                    hasNextPage: page < Math.ceil(total / limit),
                    hasPrevPage: page > 1
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GET CUTS ERROR] Get all cuts failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get cuts',
            error: error.message
        });
    }
};

// Get cut by ID
exports.getCutById = async (req, res) => {
    try {
        const { cutId } = req.params;
        
        console.log(`🎬 [GET CUT DEBUG] Getting cut by ID: ${cutId}`);
        
        const cut = await Cuts.findById(cutId)
            .populate('user_id', 'name mobile profileImage')
            .populate('likes', 'name mobile')
            .populate('comments.user_id', 'name mobile');
        
        if (!cut) {
            console.log(`❌ [GET CUT DEBUG] Cut not found: ${cutId}`);
            return res.status(404).json({
                success: false,
                message: 'Cut not found'
            });
        }
        
        // Increment views
        cut.incrementViews();
        await cut.save();
        
        console.log(`✅ [GET CUT DEBUG] Cut found: ${cut._id}, Views: ${cut.views}`);
        
        res.json({
            success: true,
            message: 'Cut retrieved successfully',
            data: {
                cut
            }
        });
        
    } catch (error) {
        console.error('❌ [GET CUT ERROR] Get cut by ID failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get cut',
            error: error.message
        });
    }
};

// Get cuts by user ID
exports.getCutsByUser = async (req, res) => {
    try {
        const { userId } = req.params;
        const { page = 1, limit = 10 } = req.query;
        
        console.log(`🎬 [GET USER CUTS DEBUG] Getting cuts for user: ${userId}, page: ${page}, limit: ${limit}`);
        
        const result = await Cuts.getCutsByUser(userId, page, limit);
        
        res.json({
            success: true,
            message: 'User cuts retrieved successfully',
            data: {
                cuts: result.cuts,
                pagination: {
                    currentPage: result.page,
                    totalPages: result.totalPages,
                    totalCuts: result.total,
                    hasNextPage: result.page < result.totalPages,
                    hasPrevPage: result.page > 1
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GET USER CUTS ERROR] Get cuts by user failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get user cuts',
            error: error.message
        });
    }
};

// Get cuts by interests
exports.getCutsByInterests = async (req, res) => {
    try {
        const { interests } = req.params;
        const { page = 1, limit = 10 } = req.query;
        
        console.log(`🎬 [GET INTERESTS CUTS DEBUG] Getting cuts for interests: ${interests}, page: ${page}, limit: ${limit}`);
        
        const interestsArray = interests.split(',').map(i => i.trim());
        const result = await Cuts.getCutsByInterests(interestsArray, page, limit);
        
        res.json({
            success: true,
            message: 'Cuts by interests retrieved successfully',
            data: {
                cuts: result.cuts,
                interests: interestsArray,
                pagination: {
                    currentPage: result.page,
                    totalPages: result.totalPages,
                    totalCuts: result.total,
                    hasNextPage: result.page < result.totalPages,
                    hasPrevPage: result.page > 1
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GET INTERESTS CUTS ERROR] Get cuts by interests failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get cuts by interests',
            error: error.message
        });
    }
};

// Get trending cuts
exports.getTrendingCuts = async (req, res) => {
    try {
        const { page = 1, limit = 10 } = req.query;
        
        console.log(`🎬 [GET TRENDING CUTS DEBUG] Getting trending cuts, page: ${page}, limit: ${limit}`);
        
        const result = await Cuts.getTrendingCuts(page, limit);
        
        res.json({
            success: true,
            message: 'Trending cuts retrieved successfully',
            data: {
                cuts: result.cuts,
                pagination: {
                    currentPage: result.page,
                    totalPages: result.totalPages,
                    totalCuts: result.total,
                    hasNextPage: result.page < result.totalPages,
                    hasPrevPage: result.page > 1
                }
            }
        });
        
    } catch (error) {
        console.error('❌ [GET TRENDING CUTS ERROR] Get trending cuts failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get trending cuts',
            error: error.message
        });
    }
};

// Update cut
exports.updateCut = async (req, res) => {
    try {
        const { cutId } = req.params;
        const updateData = req.body;
        const userId = req.user._id;
        
        console.log(`🎬 [UPDATE CUT DEBUG] Updating cut: ${cutId} by user: ${userId}`);
        console.log(`🎬 [UPDATE CUT DEBUG] Update data:`, updateData);
        
        const cut = await Cuts.findById(cutId);
        
        if (!cut) {
            console.log(`❌ [UPDATE CUT DEBUG] Cut not found: ${cutId}`);
            return res.status(404).json({
                success: false,
                message: 'Cut not found'
            });
        }
        
        // Check if user owns the cut
        if (cut.user_id.toString() !== userId.toString()) {
            console.log(`❌ [UPDATE CUT DEBUG] Access denied for user: ${userId}`);
            return res.status(403).json({
                success: false,
                message: 'Access denied. You can only update your own cuts.'
            });
        }
        
        // Update only provided fields
        const allowedFields = ['title', 'description', 'visibility', 'interests', 'tags'];
        Object.keys(updateData).forEach(key => {
            if (allowedFields.includes(key) && updateData[key] !== undefined) {
                cut[key] = updateData[key];
                console.log(`🎬 [UPDATE CUT DEBUG] Updated ${key}: ${updateData[key]}`);
            }
        });
        
        await cut.save();
        
        console.log(`✅ [UPDATE CUT DEBUG] Cut updated successfully: ${cut._id}`);
        
        res.json({
            success: true,
            message: 'Cut updated successfully',
            data: {
                cut
            }
        });
        
    } catch (error) {
        console.error('❌ [UPDATE CUT ERROR] Update cut failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to update cut',
            error: error.message
        });
    }
};

// Delete cut
exports.deleteCut = async (req, res) => {
    try {
        const { cutId } = req.params;
        const userId = req.user._id;
        
        console.log(`🎬 [DELETE CUT DEBUG] Deleting cut: ${cutId} by user: ${userId}`);
        
        const cut = await Cuts.findById(cutId);
        
        if (!cut) {
            console.log(`❌ [DELETE CUT DEBUG] Cut not found: ${cutId}`);
            return res.status(404).json({
                success: false,
                message: 'Cut not found'
            });
        }
        
        // Check if user owns the cut
        if (cut.user_id.toString() !== userId.toString()) {
            console.log(`❌ [DELETE CUT DEBUG] Access denied for user: ${userId}`);
            return res.status(403).json({
                success: false,
                message: 'Access denied. You can only delete your own cuts.'
            });
        }
        
        // Delete video file from filesystem
        if (cut.video && cut.video.filePath) {
            try {
                if (fs.existsSync(cut.video.filePath)) {
                    fs.unlinkSync(cut.video.filePath);
                    console.log(`🎬 [DELETE CUT DEBUG] Video file deleted: ${cut.video.filePath}`);
                }
                
                // Delete thumbnail if exists
                if (cut.video.thumbnail) {
                    const thumbnailPath = path.join(__dirname, '..', 'uploads', 'cuts', path.basename(cut.video.thumbnail));
                    if (fs.existsSync(thumbnailPath)) {
                        fs.unlinkSync(thumbnailPath);
                        console.log(`🎬 [DELETE CUT DEBUG] Thumbnail deleted: ${thumbnailPath}`);
                    }
                }
            } catch (fileError) {
                console.error(`❌ [DELETE CUT DEBUG] Failed to delete video file:`, fileError);
            }
        }
        
        // Soft delete (set isActive to false)
        cut.isActive = false;
        await cut.save();
        
        console.log(`✅ [DELETE CUT DEBUG] Cut soft deleted successfully: ${cut._id}`);
        
        res.json({
            success: true,
            message: 'Cut deleted successfully'
        });
        
    } catch (error) {
        console.error('❌ [DELETE CUT ERROR] Delete cut failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to delete cut',
            error: error.message
        });
    }
};

// Like/Unlike cut
exports.toggleLike = async (req, res) => {
    try {
        const { cutId } = req.params;
        const userId = req.user._id;
        
        console.log(`🎬 [TOGGLE LIKE DEBUG] Toggling like for cut: ${cutId} by user: ${userId}`);
        
        const cut = await Cuts.findById(cutId);
        
        if (!cut) {
            console.log(`❌ [TOGGLE LIKE DEBUG] Cut not found: ${cutId}`);
            return res.status(404).json({
                success: false,
                message: 'Cut not found'
            });
        }
        
        const isLiked = cut.likes.includes(userId);
        let action;
        
        if (isLiked) {
            cut.removeLike(userId);
            action = 'unliked';
            console.log(`🎬 [TOGGLE LIKE DEBUG] User unliked cut`);
        } else {
            cut.addLike(userId);
            action = 'liked';
            console.log(`🎬 [TOGGLE LIKE DEBUG] User liked cut`);
        }
        
        await cut.save();
        
        res.json({
            success: true,
            message: `Cut ${action} successfully`,
            data: {
                isLiked: !isLiked,
                likesCount: cut.engagement.likesCount
            }
        });
        
    } catch (error) {
        console.error('❌ [TOGGLE LIKE ERROR] Toggle like failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to toggle like',
            error: error.message
        });
    }
};

// Add comment to cut
exports.addComment = async (req, res) => {
    try {
        const { cutId } = req.params;
        const { comment } = req.body;
        const userId = req.user._id;
        
        console.log(`🎬 [ADD COMMENT DEBUG] Adding comment to cut: ${cutId} by user: ${userId}`);
        console.log(`🎬 [ADD COMMENT DEBUG] Comment: "${comment}"`);
        
        const cut = await Cuts.findById(cutId);
        
        if (!cut) {
            console.log(`❌ [ADD COMMENT DEBUG] Cut not found: ${cutId}`);
            return res.status(404).json({
                success: false,
                message: 'Cut not found'
            });
        }
        
        cut.addComment(userId, comment);
        await cut.save();
        
        // Populate the new comment
        await cut.populate('comments.user_id', 'name mobile');
        
        const newComment = cut.comments[cut.comments.length - 1];
        
        console.log(`✅ [ADD COMMENT DEBUG] Comment added successfully`);
        
        res.json({
            success: true,
            message: 'Comment added successfully',
            data: {
                comment: newComment,
                commentsCount: cut.engagement.commentsCount
            }
        });
        
    } catch (error) {
        console.error('❌ [ADD COMMENT ERROR] Add comment failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to add comment',
            error: error.message
        });
    }
};

// Share cut
exports.shareCut = async (req, res) => {
    try {
        const { cutId } = req.params;
        const userId = req.user._id;
        
        console.log(`🎬 [SHARE CUT DEBUG] Sharing cut: ${cutId} by user: ${userId}`);
        
        const cut = await Cuts.findById(cutId);
        
        if (!cut) {
            console.log(`❌ [SHARE CUT DEBUG] Cut not found: ${cutId}`);
            return res.status(404).json({
                success: false,
                message: 'Cut not found'
            });
        }
        
        const wasShared = cut.addShare(userId);
        await cut.save();
        
        console.log(`✅ [SHARE CUT DEBUG] Cut shared successfully`);
        
        res.json({
            success: true,
            message: 'Cut shared successfully',
            data: {
                sharesCount: cut.engagement.sharesCount
            }
        });
        
    } catch (error) {
        console.error('❌ [SHARE CUT ERROR] Share cut failed:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to share cut',
            error: error.message
        });
    }
};

// Get cuts by interests
exports.getCutsByInterests = async (req, res) => {

    try {

        const { interests } = req.params;

        const { page = 1, limit = 10 } = req.query;

        

        console.log(`🎬 [GET INTERESTS CUTS DEBUG] Getting cuts for interests: ${interests}, page: ${page}, limit: ${limit}`);

        

        const interestsArray = interests.split(',').map(i => i.trim());

        const result = await Cuts.getCutsByInterests(interestsArray, page, limit);

        

        res.json({

            success: true,

            message: 'Cuts by interests retrieved successfully',

            data: {

                cuts: result.cuts,

                interests: interestsArray,

                pagination: {

                    currentPage: result.page,

                    totalPages: result.totalPages,

                    totalCuts: result.total,

                    hasNextPage: result.page < result.totalPages,

                    hasPrevPage: result.page > 1

                }

            }

        });

        

    } catch (error) {

        console.error('❌ [GET INTERESTS CUTS ERROR] Get cuts by interests failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to get cuts by interests',

            error: error.message

        });

    }

};



// Get trending cuts

exports.getTrendingCuts = async (req, res) => {

    try {

        const { page = 1, limit = 10 } = req.query;

        

        console.log(`🎬 [GET TRENDING CUTS DEBUG] Getting trending cuts, page: ${page}, limit: ${limit}`);

        

        const result = await Cuts.getTrendingCuts(page, limit);

        

        res.json({

            success: true,

            message: 'Trending cuts retrieved successfully',

            data: {

                cuts: result.cuts,

                pagination: {

                    currentPage: result.page,

                    totalPages: result.totalPages,

                    totalCuts: result.total,

                    hasNextPage: result.page < result.totalPages,

                    hasPrevPage: result.page > 1

                }

            }

        });

        

    } catch (error) {

        console.error('❌ [GET TRENDING CUTS ERROR] Get trending cuts failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to get trending cuts',

            error: error.message

        });

    }

};



// Update cut

exports.updateCut = async (req, res) => {

    try {

        const { cutId } = req.params;

        const updateData = req.body;

        const userId = req.user._id;

        

        console.log(`🎬 [UPDATE CUT DEBUG] Updating cut: ${cutId} by user: ${userId}`);

        console.log(`🎬 [UPDATE CUT DEBUG] Update data:`, updateData);

        

        const cut = await Cuts.findById(cutId);

        

        if (!cut) {

            console.log(`❌ [UPDATE CUT DEBUG] Cut not found: ${cutId}`);

            return res.status(404).json({

                success: false,

                message: 'Cut not found'

            });

        }

        

        // Check if user owns the cut

        if (cut.user_id.toString() !== userId.toString()) {

            console.log(`❌ [UPDATE CUT DEBUG] Access denied for user: ${userId}`);

            return res.status(403).json({

                success: false,

                message: 'Access denied. You can only update your own cuts.'

            });

        }

        

        // Update only provided fields

        const allowedFields = ['title', 'description', 'visibility', 'interests', 'tags'];

        Object.keys(updateData).forEach(key => {

            if (allowedFields.includes(key) && updateData[key] !== undefined) {

                cut[key] = updateData[key];

                console.log(`🎬 [UPDATE CUT DEBUG] Updated ${key}: ${updateData[key]}`);

            }

        });

        

        await cut.save();

        

        console.log(`✅ [UPDATE CUT DEBUG] Cut updated successfully: ${cut._id}`);

        

        res.json({

            success: true,

            message: 'Cut updated successfully',

            data: {

                cut

            }

        });

        

    } catch (error) {

        console.error('❌ [UPDATE CUT ERROR] Update cut failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to update cut',

            error: error.message

        });

    }

};



// Delete cut

exports.deleteCut = async (req, res) => {

    try {

        const { cutId } = req.params;

        const userId = req.user._id;

        

        console.log(`🎬 [DELETE CUT DEBUG] Deleting cut: ${cutId} by user: ${userId}`);

        

        const cut = await Cuts.findById(cutId);

        

        if (!cut) {

            console.log(`❌ [DELETE CUT DEBUG] Cut not found: ${cutId}`);

            return res.status(404).json({

                success: false,

                message: 'Cut not found'

            });

        }

        

        // Check if user owns the cut

        if (cut.user_id.toString() !== userId.toString()) {

            console.log(`❌ [DELETE CUT DEBUG] Access denied for user: ${userId}`);

            return res.status(403).json({

                success: false,

                message: 'Access denied. You can only delete your own cuts.'

            });

        }

        

        // Delete video file from filesystem

        if (cut.video && cut.video.filePath) {

            try {

                if (fs.existsSync(cut.video.filePath)) {

                    fs.unlinkSync(cut.video.filePath);

                    console.log(`🎬 [DELETE CUT DEBUG] Video file deleted: ${cut.video.filePath}`);

                }

                

                // Delete thumbnail if exists

                if (cut.video.thumbnail) {

                    const thumbnailPath = path.join(__dirname, '..', 'uploads', 'cuts', path.basename(cut.video.thumbnail));

                    if (fs.existsSync(thumbnailPath)) {

                        fs.unlinkSync(thumbnailPath);

                        console.log(`🎬 [DELETE CUT DEBUG] Thumbnail deleted: ${thumbnailPath}`);

                    }

                }

            } catch (fileError) {

                console.error(`❌ [DELETE CUT DEBUG] Failed to delete video file:`, fileError);

            }

        }

        

        // Soft delete (set isActive to false)

        cut.isActive = false;

        await cut.save();

        

        console.log(`✅ [DELETE CUT DEBUG] Cut soft deleted successfully: ${cut._id}`);

        

        res.json({

            success: true,

            message: 'Cut deleted successfully'

        });

        

    } catch (error) {

        console.error('❌ [DELETE CUT ERROR] Delete cut failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to delete cut',

            error: error.message

        });

    }

};



// Like/Unlike cut

exports.toggleLike = async (req, res) => {

    try {

        const { cutId } = req.params;

        const userId = req.user._id;

        

        console.log(`🎬 [TOGGLE LIKE DEBUG] Toggling like for cut: ${cutId} by user: ${userId}`);

        

        const cut = await Cuts.findById(cutId);

        

        if (!cut) {

            console.log(`❌ [TOGGLE LIKE DEBUG] Cut not found: ${cutId}`);

            return res.status(404).json({

                success: false,

                message: 'Cut not found'

            });

        }

        

        const isLiked = cut.likes.includes(userId);

        let action;

        

        if (isLiked) {

            cut.removeLike(userId);

            action = 'unliked';

            console.log(`🎬 [TOGGLE LIKE DEBUG] User unliked cut`);

        } else {

            cut.addLike(userId);

            action = 'liked';

            console.log(`🎬 [TOGGLE LIKE DEBUG] User liked cut`);

        }

        

        await cut.save();

        

        res.json({

            success: true,

            message: `Cut ${action} successfully`,

            data: {

                isLiked: !isLiked,

                likesCount: cut.engagement.likesCount

            }

        });

        

    } catch (error) {

        console.error('❌ [TOGGLE LIKE ERROR] Toggle like failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to toggle like',

            error: error.message

        });

    }

};



// Add comment to cut

exports.addComment = async (req, res) => {

    try {

        const { cutId } = req.params;

        const { comment } = req.body;

        const userId = req.user._id;

        

        console.log(`🎬 [ADD COMMENT DEBUG] Adding comment to cut: ${cutId} by user: ${userId}`);

        console.log(`🎬 [ADD COMMENT DEBUG] Comment: "${comment}"`);

        

        const cut = await Cuts.findById(cutId);

        

        if (!cut) {

            console.log(`❌ [ADD COMMENT DEBUG] Cut not found: ${cutId}`);

            return res.status(404).json({

                success: false,

                message: 'Cut not found'

            });

        }

        

        cut.addComment(userId, comment);

        await cut.save();

        

        // Populate the new comment

        await cut.populate('comments.user_id', 'name mobile');

        

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

        

        console.log(`✅ [ADD COMMENT DEBUG] Comment added successfully`);

        

        res.json({

            success: true,

            message: 'Comment added successfully',

            data: {

                comment: newComment,

                commentsCount: cut.engagement.commentsCount

            }

        });

        

    } catch (error) {

        console.error('❌ [ADD COMMENT ERROR] Add comment failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to add comment',

            error: error.message

        });

    }

};



// Share cut

exports.shareCut = async (req, res) => {

    try {

        const { cutId } = req.params;

        const userId = req.user._id;

        

        console.log(`🎬 [SHARE CUT DEBUG] Sharing cut: ${cutId} by user: ${userId}`);

        

        const cut = await Cuts.findById(cutId);

        

        if (!cut) {

            console.log(`❌ [SHARE CUT DEBUG] Cut not found: ${cutId}`);

            return res.status(404).json({

                success: false,

                message: 'Cut not found'

            });

        }

        

        const wasShared = cut.addShare(userId);

        await cut.save();

        

        console.log(`✅ [SHARE CUT DEBUG] Cut shared successfully`);

        

        res.json({

            success: true,

            message: 'Cut shared successfully',

            data: {

                sharesCount: cut.engagement.sharesCount

            }

        });

        

    } catch (error) {

        console.error('❌ [SHARE CUT ERROR] Share cut failed:', error);

        res.status(500).json({

            success: false,

            message: 'Failed to share cut',

            error: error.message

        });

    }

};


