const mongoose = require('mongoose');

const airportRouteSchema = new mongoose.Schema({
    airportName: {
        type: String,
        required: [true, 'Airport name is required'],
        trim: true
    },
    airportCode: {
        type: String,
        trim: true,
        uppercase: true  // IATA code like "BLR", "DEL"
    },
    cityName: {
        type: String,
        required: [true, 'City name is required'],
        trim: true
    },
    coordinates: {
        type: { type: String, enum: ['Point'], default: 'Point' },
        coordinates: { type: [Number], default: [0, 0] } // [longitude, latitude] of the AIRPORT
    },
    cityCoordinates: {
        type: { type: String, enum: ['Point'], default: 'Point' },
        coordinates: { type: [Number], default: [0, 0] } // [longitude, latitude] of the CITY Center
    },
    routeType: {
        type: String,
        enum: ['from_airport', 'to_airport'],
        required: [true, 'Route type is required']
    },
    slug: {
        type: String,
        unique: true,
        lowercase: true,
        trim: true
    },
    zone: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Zone',
        required: [true, 'Zone is required for pricing calculation']
    },
    distance: {
        type: Number,
        default: 0  // in kilometers
    },
    duration: {
        type: Number,
        default: 0  // in minutes
    },
    isDistanceManual: {
        type: Boolean,
        default: false
    },
    metaTitle: {
        type: String,
        trim: true
    },
    metaDescription: {
        type: String,
        trim: true
    },
    pageContent: {
        type: String,
        default: ''
    },
    faqs: [{
        question: String,
        answer: String
    }],
    popularPlaces: [{
        name: String,
        description: String,
        imageUrl: String
    }],
    displayOrder: {
        type: Number,
        default: 0
    },
    isActive: {
        type: Boolean,
        default: true,
        index: true
    },
    createdBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
}, { timestamps: true });

// Auto-generate slug before saving
airportRouteSchema.pre('save', function (next) {
    if (!this.slug || this.isModified('airportName') || this.isModified('cityName') || this.isModified('routeType')) {
        const airport = this.airportName.toLowerCase().replace(/\s+/g, '-');
        const city = this.cityName.toLowerCase().replace(/\s+/g, '-');

        if (this.routeType === 'from_airport') {
            this.slug = `cab-from-${airport}`;
        } else {
            this.slug = `${city}-to-${airport}-cab`;
        }
    }
    next();
});

// Index for faster queries
airportRouteSchema.index({ airportName: 1, cityName: 1, routeType: 1 }, { unique: true });
airportRouteSchema.index({ displayOrder: 1 });

module.exports = mongoose.model('AirportRoute', airportRouteSchema);
