const mongoose = require('mongoose');

const newsCategorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Category name is required'],
        unique: true,
        trim: true,
        maxlength: [50, 'Category name cannot exceed 50 characters']
    },
    
    slug: {
        type: String,
        required: [true, 'Category slug is required'],
        unique: true,
        trim: true,
        lowercase: true,
        match: [/^[a-z0-9-]+$/, 'Slug must contain only lowercase letters, numbers, and hyphens']
    },
    
    description: {
        type: String,
        trim: true,
        maxlength: [200, 'Description cannot exceed 200 characters']
    },
    
    keywords: [{
        type: String,
        trim: true,
        lowercase: true
    }],
    
    isActive: {
        type: Boolean,
        default: true
    },
    
    sortOrder: {
        type: Number,
        default: 0
    },
    
    icon: {
        type: String,
        trim: true
    },
    
    color: {
        type: String,
        trim: true,
        match: [/^#[0-9A-Fa-f]{6}$/, 'Color must be a valid hex color code']
    },
    
    // Statistics
    articleCount: {
        type: Number,
        default: 0
    },
    
    lastUpdated: {
        type: Date,
        default: Date.now
    }
}, {
    timestamps: true
});

// Index for better query performance
newsCategorySchema.index({ slug: 1 });
newsCategorySchema.index({ isActive: 1, sortOrder: 1 });

// Pre-save middleware to update lastUpdated
newsCategorySchema.pre('save', function(next) {
    this.lastUpdated = new Date();
    next();
});

// Static method to get active categories
newsCategorySchema.statics.getActiveCategories = function() {
    return this.find({ isActive: true }).sort({ sortOrder: 1, name: 1 });
};

// Method to update article count
newsCategorySchema.methods.updateArticleCount = async function() {
    const News = mongoose.model('News');
    const count = await News.countDocuments({ 
        category: this.slug, 
        isActive: true 
    });
    this.articleCount = count;
    await this.save();
    return count;
};

// Virtual for display name
newsCategorySchema.virtual('displayName').get(function() {
    return this.name || this.slug;
});

// Ensure virtual fields are serialized
newsCategorySchema.set('toJSON', { virtuals: true });
newsCategorySchema.set('toObject', { virtuals: true });

module.exports = mongoose.model('NewsCategory', newsCategorySchema);
