const mongoose = require('mongoose');

const blogCategorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    trim: true,
    unique: true // "Permanent Residency (PR)"
  },
  slug: {
    type: String,
    required: true,
    unique: true,
    trim: true // "permanent-residency"
  },
  postCount: {
    type: Number,
    default: 0 // "(04)"
  },
  description: {
    type: String,
    default: ''
  },
  isActive: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

// Indexes
blogCategorySchema.index({ isActive: 1, name: 1 });

// Remove __v from JSON output
blogCategorySchema.set('toJSON', {
  transform: function(doc, ret) {
    delete ret.__v;
    return ret;
  }
});

// Pre-save middleware
blogCategorySchema.pre('save', function(next) {
  // Auto-generate slug if not provided
  if (!this.slug && this.name) {
    this.slug = this.name
      .toLowerCase()
      .replace(/[^a-z0-9\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-')
      .trim('-');
  }
  
  next();
});

// Static methods
blogCategorySchema.statics.getActive = function() {
  return this.find({ isActive: true }).sort({ name: 1 });
};

// Method to update post count
blogCategorySchema.methods.updatePostCount = async function() {
  const Blog = require('./blog');
  const count = await Blog.countDocuments({ 
    category: { $in: [this.name] }, // Tìm trong array categories
    status: 'published' 
  });
  this.postCount = count;
  await this.save();
  return count;
};

module.exports = mongoose.model('BlogCategory', blogCategorySchema);