import mongoose, { Document, Schema } from 'mongoose';

export interface ICategory extends Document {
  name: string;
  slug: string;
  description?: string;
  parent?: mongoose.Types.ObjectId;
  level: number;
  image?: string;
  isActive: boolean;
  isevent?: boolean;
  createdAt: Date;
  updatedAt: Date;
}

// In your Category model file
const CategorySchema: Schema = new Schema({
  name: {
    type: String,
    required: [true, 'Category name is required'],
    trim: true,
    maxlength: [100, 'Category name cannot exceed 100 characters']
  },
  slug: {
    type: String,
    required: [true, 'Category slug is required'],
    unique: true,
    trim: true,
    lowercase: true
  },
  description: {
    type: String,
    trim: true,
    maxlength: [500, 'Description cannot exceed 500 characters']
  },
  parent: {
    type: Schema.Types.ObjectId,
    ref: 'Category',
    default: null
  },
  level: {
    type: Number,
    default: 1,
    min: 1,
    max: 3
  },
  image: {  // ← ADD THIS FIELD
    type: String,
    trim: true,
    default: null
  },
  isActive: {
    type: Boolean,
    default: true
  },
  isevent: {
    type: Boolean,
    default: false
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// Virtual for subcategories
CategorySchema.virtual('subcategories', {
  ref: 'Category',
  localField: '_id',
  foreignField: 'parent'
});

// Index for better performance
CategorySchema.index({ parent: 1, name: 1 });
CategorySchema.index({ slug: 1 });

// Pre-save middleware to generate slug and set level
CategorySchema.pre<ICategory>('save', async function () {
  // Generate slug
  if (this.isModified('name') && !this.slug) {
    this.slug = this.name
      .toLowerCase()
      .replace(/[^a-zA-Z0-9]/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-|-$/g, '');
  }

  // Set level
  if (this.parent) {
    const parentCategory = await mongoose
      .model('Category')
      .findById(this.parent);

    if (parentCategory) {
      this.level = parentCategory.level + 1;
    }
  } else {
    this.level = 1;
  }
});

export default mongoose.models.Category || mongoose.model<ICategory>('Category', CategorySchema);