const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const timestamp = require('mongoose-timestamp');

const AcademyCategorySchema = new mongoose.Schema({
    title: {
        type: String,
        required: [true, 'عنوان دسته‌بندی الزامی است'],
        trim: true,
        minLength: [2, 'عنوان باید حداقل ۲ کاراکتر باشد'],
        maxLength: [100, 'عنوان باید حداکثر ۱۰۰ کاراکتر باشد'],
        unique: true,
        index: true,
    },
    slug: {
        type: String,
        required: true,
        unique: true,
        lowercase: true,
        trim: true,
        index: true,
    },
    description: {
        type: String,
        required: false,
        trim: true,
        maxLength: 500,
        default: null,
    },
    icon: {
        type: String,
        required: false,
        default: null,
    },
    color: {
        type: String,
        required: false,
        default: '#3B82F6',
        match: /^#[0-9A-F]{6}$/i,
    },
    parent: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'AcademyCategory',
        required: false,
        default: null,
        index: true,
    },
    level: {
        type: Number,
        required: true,
        default: 0,
        min: 0,
        max: 3,
    },
    order: {
        type: Number,
        required: true,
        default: 0,
        index: true,
    },
    image: {
        type: String,
        required: false,
        default: null,
    },
    course_count: {
        type: Number,
        required: true,
        default: 0,
        min: 0,
    },
    status: {
        type: String,
        enum: ['active', 'inactive', 'deleted'],
        required: true,
        default: 'active',
        index: true,
    },
    is_featured: {
        type: Boolean,
        required: true,
        default: false,
        index: true,
    },
    seo_title: {
        type: String,
        required: false,
        trim: true,
        maxLength: 70,
    },
    seo_description: {
        type: String,
        required: false,
        trim: true,
        maxLength: 160,
    },
    created_by: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true,
    },
    updated_by: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: false,
    },
}, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true }
});

// Virtual برای زیردسته‌ها
AcademyCategorySchema.virtual('children', {
    ref: 'AcademyCategory',
    localField: '_id',
    foreignField: 'parent',
    justOne: false,
    options: { sort: { order: 1, title: 1 } }
});

// Virtual برای دوره‌های این دسته
AcademyCategorySchema.virtual('courses', {
    ref: 'Course',
    localField: '_id',
    foreignField: 'category_id',
    justOne: false,
    match: { status: 'accept' }
});

// Middleware: قبل از save
AcademyCategorySchema.pre('save', async function(next) {
    if (this.isModified('title') || this.isNew) {
        // تولید slug
        this.slug = this.title
            .replace(/[^\u0600-\u06FF\uFB8A\u067E\u0686\u06AF\u200C\uFB8E\u0698a-zA-Z0-9\s]/g, '')
            .trim()
            .replace(/\s+/g, '-')
            .toLowerCase();
        
        // اگه parent داره، سطح رو محاسبه کن
        if (this.parent) {
            const parent = await this.constructor.findById(this.parent);
            if (parent) {
                this.level = parent.level + 1;
            }
        } else {
            this.level = 0;
        }
    }
    next();
});

// استاتیک متدها
AcademyCategorySchema.statics = {
    // دریافت درخت دسته‌بندی‌ها
    async getTree() {
        const categories = await this.find({ status: 'active', parent: null })
            .sort({ order: 1, title: 1 })
            .populate({
                path: 'children',
                match: { status: 'active' },
                options: { sort: { order: 1, title: 1 } },
                populate: {
                    path: 'children',
                    match: { status: 'active' },
                    options: { sort: { order: 1, title: 1 } }
                }
            });
        return categories;
    },

    // افزایش تعداد دوره‌ها
    async incrementCourseCount(categoryId, increment = 1) {
        return this.findByIdAndUpdate(categoryId, {
            $inc: { course_count: increment }
        });
    },

    // دریافت دسته‌بندی با اسلاگ
    async getBySlug(slug) {
        return this.findOne({ slug, status: 'active' })
            .populate('children')
            .populate('parent');
    }
};

AcademyCategorySchema.plugin(timestamp);
AcademyCategorySchema.plugin(mongoosePaginate);

module.exports = mongoose.model('AcademyCategory', AcademyCategorySchema);