const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const UserSchema = new mongoose.Schema(
    {
        name: { type: String, required: true },
        phone: { type: String, required: true, unique: true },
        email: { type: String, unique: true, sparse: true },
        password: { type: String, required: true },
        resetCode: { type: String },
        resetCodeExpires: { type: Date },

        // ✅ حافظنا على الأدوار القديمة
        role: {
            type: String,
            enum: ['customer', 'client', 'captain', 'admin', 'merchant'],
            default: 'client'
        },

        // ✅ حافظنا على نوع المركبة للكابتن
        vehicleType: {
            type: String,
            enum: ['bicycle', 'electric', 'motorcycle']
        },
        currentLocation: {
            lat: { type: Number },
            lng: { type: Number },
            updatedAt: { type: Date }
        },

        isActive: { type: Boolean, default: true }, // ← Admin-controlled: false = account suspended

        // ← Captain-controlled: whether they are available to receive orders (does NOT affect login)
        isAvailableForWork: { type: Boolean, default: false },

        // ✅ FIX #17: Captains default to 'pending' (require admin approval); others default to 'approved'
        approvalStatus: {
            type: String,
            enum: ['pending', 'approved', 'rejected'],
            default: function () {
                return (this.role === 'captain' || this.role === 'merchant') ? 'pending' : 'approved';
            }
        },
        documents: {
            driverLicense: { type: String },  // URL الرخصة
            profilePhoto: { type: String },   // صورة شخصية
            vehiclePhoto: { type: String }    // صورة المركبة
        },
        rejectionReason: { type: String },

        // 👇 الإضافات الجديدة للتفعيل والأمان 👇
        isVerified: { type: Boolean, default: false },
        verificationCode: { type: String },
        verificationCodeExpires: { type: Date }, // ⏰ وقت انتهاء الكود

        isWhatsappSubscribed: { type: Boolean, default: false }, // ✅ WhatsApp Subscription
        otpCode: { type: String }, // ✅ For SMS/WhatsApp OTP
        otpExpires: { type: Date },

        // 🌟 Rating System
        ratingSum: { type: Number, default: 0 },
        ratingCount: { type: Number, default: 0 },
        averageRating: { type: Number, default: 5.0 }, // Default starts high or neutral

        // 💰 Earnings (Legacy — positive accumulation)
        wallet: { type: Number, default: 0 },

        // 💳 Negative Wallet & Credit Limit System
        // wallet_balance: صافي رصيد المحفظة (يبدأ من 0 وينخفض مع كل طلب نقدي)
        // credit_limit: الحد الأقصى للمديونية المسموحة (سالب)
        // is_blocked: هل الكابتن محجوب بسبب تجاوز الحد الائتماني
        wallet_balance: { type: Number, default: 0 },
        credit_limit: { type: Number, default: -5000 },
        is_blocked: { type: Boolean, default: false },

        // 🔔 FCM for Native Notifications
        fcmToken: { type: String }
    },
    { timestamps: true }
);

UserSchema.pre('save', async function (next) {
    if (!this.isModified('password')) return next();
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
});

UserSchema.methods.matchPassword = async function (enteredPassword) {
    return await bcrypt.compare(enteredPassword, this.password);
};

// 🔒 PERFORMANCE: Database Indexes
// unique: true already creates indexes for these fields; avoid duplicate indexes
UserSchema.index({ role: 1, isActive: 1 }); // For finding active captains

module.exports = mongoose.model('User', UserSchema);
