const mongoose = require('mongoose');

const cutsSchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, 'Title is required'],
        trim: true,
        maxlength: [200, 'Title cannot exceed 200 characters'],
        index: true
    },
    
    description: {
        type: String,
        required: [true, 'Description is required'],
        trim: true,
        maxlength: [1000, 'Description cannot exceed 1000 characters']
    },
    
    visibility: {
        type: String,
        enum: ['public', 'private', 'friends', 'group'],
        default: 'public',
        required: true,
        index: true
    },
    
    interests: [{
        type: String,
        trim: true,
        maxlength: [50, 'Interest name cannot exceed 50 characters']
    }],
    
    video: {
        fileName: {
            type: String,
            trim: true
        },
        filePath: {
            type: String,
            trim: true
        },
        url: {
            type: String,
            trim: true
        },
        originalName: {
            type: String,
            trim: true
        },
        size: {
            type: Number,
            min: [0, 'File size cannot be negative']
        },
        mimeType: {
            type: String,
            trim: true
        },
        duration: {
            type: Number, // Duration in seconds
            min: [0, 'Duration cannot be negative']
        },
        thumbnail: {
            type: String,
            trim: true
        },
        fileHash: {
            type: String,
            trim: true
        }
    },
    
    user_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: [true, 'User ID is required'],
        index: true
    },
    
    // Additional fields for engagement
    likes: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }],
    
    comments: [{
        user_id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User',
            required: true
        },
        comment: {
            type: String,
            required: true,
            trim: true,
            maxlength: [500, 'Comment cannot exceed 500 characters']
        },
        createdAt: {
            type: Date,
            default: Date.now
        }
    }],
    
    shares: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }],
    
    views: {
        type: Number,
        default: 0,
        min: [0, 'Views cannot be negative']
    },
    
    // Status fields
    isActive: {
        type: Boolean,
        default: true,
        index: true
    },
    
    isPinned: {
        type: Boolean,
        default: false
    },
    
    // Tags for categorization
    tags: [{
        type: String,
        trim: true,
        maxlength: [30, 'Tag cannot exceed 30 characters']
    }],
    
    // Engagement metrics
    engagement: {
        likesCount: {
            type: Number,
            default: 0
        },
        commentsCount: {
            type: Number,
            default: 0
        },
        sharesCount: {
            type: Number,
            default: 0
        }
    }
}, {
    timestamps: true,
    collection: 'cuts'
});

// Indexes for efficient queries
cutsSchema.index({ user_id: 1, createdAt: -1 });
cutsSchema.index({ visibility: 1, isActive: 1, createdAt: -1 });
cutsSchema.index({ interests: 1 });
cutsSchema.index({ tags: 1 });
cutsSchema.index({ 'engagement.likesCount': -1 });
cutsSchema.index({ 'engagement.commentsCount': -1 });

// Virtual for total engagement
cutsSchema.virtual('totalEngagement').get(function() {
    return this.engagement.likesCount + this.engagement.commentsCount + this.engagement.sharesCount;
});

// Method to add like
cutsSchema.methods.addLike = function(userId) {
    if (!this.likes.includes(userId)) {
        this.likes.push(userId);
        this.engagement.likesCount = this.likes.length;
        return true;
    }
    return false;
};

// Method to remove like
cutsSchema.methods.removeLike = function(userId) {
    const index = this.likes.indexOf(userId);
    if (index > -1) {
        this.likes.splice(index, 1);
        this.engagement.likesCount = this.likes.length;
        return true;
    }
    return false;
};

// Method to add comment
cutsSchema.methods.addComment = function(userId, comment) {
    this.comments.push({
        user_id: userId,
        comment: comment,
        createdAt: new Date()
    });
    this.engagement.commentsCount = this.comments.length;
};

// Method to add share
cutsSchema.methods.addShare = function(userId) {
    if (!this.shares.includes(userId)) {
        this.shares.push(userId);
        this.engagement.sharesCount = this.shares.length;
        return true;
    }
    return false;
};

// Method to increment views
cutsSchema.methods.incrementViews = function() {
    this.views += 1;
};

// Static method to get cuts by user
cutsSchema.statics.getCutsByUser = async function(userId, page = 1, limit = 10) {
    console.log(`🎬 [CUTS DEBUG] Getting cuts for user: ${userId}, page: ${page}, limit: ${limit}`);
    
    try {
        const skip = (page - 1) * limit;
        
        const cuts = await this.find({ user_id: userId, isActive: true })
            .populate('user_id', 'name mobile profileImage')
            .sort({ createdAt: -1 })
            .skip(skip)
            .limit(limit);
        
        const total = await this.countDocuments({ user_id: userId, isActive: true });
        
        console.log(`📊 [CUTS DEBUG] Found ${cuts.length} cuts for user ${userId}`);
        
        return {
            cuts,
            total,
            page,
            totalPages: Math.ceil(total / limit)
        };
        
    } catch (error) {
        console.error(`❌ [CUTS ERROR] Get cuts by user failed:`, error);
        throw error;
    }
};

// Static method to get cuts by interests
cutsSchema.statics.getCutsByInterests = async function(interests, page = 1, limit = 10) {
    console.log(`🎬 [CUTS DEBUG] Getting cuts by interests: ${interests}, page: ${page}, limit: ${limit}`);
    
    try {
        const skip = (page - 1) * limit;
        
        const cuts = await this.find({ 
            interests: { $in: interests }, 
            isActive: true 
        })
        .populate('user_id', 'name mobile profileImage')
        .sort({ createdAt: -1 })
        .skip(skip)
        .limit(limit);
        
        const total = await this.countDocuments({ 
            interests: { $in: interests }, 
            isActive: true 
        });
        
        console.log(`📊 [CUTS DEBUG] Found ${cuts.length} cuts for interests`);
        
        return {
            cuts,
            total,
            page,
            totalPages: Math.ceil(total / limit)
        };
        
    } catch (error) {
        console.error(`❌ [CUTS ERROR] Get cuts by interests failed:`, error);
        throw error;
    }
};

// Static method to get trending cuts
cutsSchema.statics.getTrendingCuts = async function(page = 1, limit = 10) {
    console.log(`🎬 [CUTS DEBUG] Getting trending cuts, page: ${page}, limit: ${limit}`);
    
    try {
        const skip = (page - 1) * limit;
        
        const cuts = await this.find({ 
            isActive: true,
            visibility: 'public'
        })
        .populate('user_id', 'name mobile profileImage')
        .sort({ 
            'engagement.likesCount': -1, 
            'engagement.commentsCount': -1,
            'views': -1,
            createdAt: -1 
        })
        .skip(skip)
        .limit(limit);
        
        const total = await this.countDocuments({ 
            isActive: true,
            visibility: 'public'
        });
        
        console.log(`📊 [CUTS DEBUG] Found ${cuts.length} trending cuts`);
        
        return {
            cuts,
            total,
            page,
            totalPages: Math.ceil(total / limit)
        };
        
    } catch (error) {
        console.error(`❌ [CUTS ERROR] Get trending cuts failed:`, error);
        throw error;
    }
};

module.exports = mongoose.model('Cuts', cutsSchema);
