const mongoose = require('mongoose');
const logger = require('../utils/logger');

const settingsSchema = new mongoose.Schema({
    // Pricing Settings
    baseFare: {
        type: Number,
        default: 10,
        required: true,
        min: 0
    },
    costPerKm: {
        type: Number,
        default: 5,
        required: true,
        min: 0
    },
    costPerMinute: {
        type: Number,
        default: 2,
        required: true,
        min: 0
    },
    commissionRate: {
        type: Number,
        default: 0.15,
        required: true,
        min: 0,
        max: 1
    },

    // Profit Percentage (for backward compatibility with old Setting.js)
    profitPercentage: {
        type: Number,
        default: 10,
        min: 0,
        max: 100
    },

    // Admin Contact for Emergencies
    adminPhone: {
        type: String,
        default: '249112046348'
    },
    availableBanks: { 
        type: [String], 
        default: ['بنك الخرطوم', 'بنك أمدرمان الوطني', 'بنك فيصل الإسلامي'] 
    },

    // 🏦 Bank Details for Captain Payments
    bankName: {
        type: String,
        default: 'بنك الخرطوم'
    },
    bankAccountName: {
        type: String,
        default: 'ضياء الدين ابراهيم محمد'
    },
    bankAccountNumber: {
        type: String,
        default: '7702038'
    },

    // 💳 Financial System — Default Credit Limit for new captains
    defaultCreditLimit: {
        type: Number,
        default: -5000,
        max: 0
    },

    // 📱 App Update System
    appVersion: {
        type: String,
        default: '2.3.1'  // أحدث إصدار للتطبيق
    },
    minVersion: {
        type: String,
        default: '2.3.1'  // أقل إصدار مقبول (ما دونه يُجبر على التحديث)
    },
    playStoreLink: {
        type: String,
        default: 'https://play.google.com/store/apps/details?id=com.wassili.app'
    },
    forceUpdate: {
        type: Boolean,
        default: false
    },

    // Delivery Zone (Geofencing Polygon)
    deliveryZone: {
        type: [{
            lat: { type: Number, required: true },
            lng: { type: Number, required: true }
        }],
        default: [
            { lat: 15.750, lng: 32.400 },
            { lat: 15.750, lng: 32.650 },
            { lat: 15.450, lng: 32.650 },
            { lat: 15.450, lng: 32.400 }
        ]
    },

    // Metadata (updatedAt is auto-managed by timestamps: true)
    updatedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
}, {
    timestamps: true
});

// Ensure only one settings document exists — always returns the NEWEST doc
settingsSchema.statics.getSettings = async function () {
    const count = await this.countDocuments();

    if (count === 0) {
        const created = await this.create({});
        return created.toObject();
    }

    // ✅ ALWAYS sort by updatedAt:-1 — newest doc wins
    const newest = await this.findOne().sort({ updatedAt: -1 }).lean();

    // Auto-deduplicate if needed (awaited for consistency)
    if (count > 1) {
        const r = await this.deleteMany({ _id: { $ne: newest._id } });
        logger.warn({ deletedCount: r.deletedCount }, 'Settings: removed duplicate docs');
    }

    return newest;
};

// Helper method to get profit percentage
settingsSchema.statics.getProfitPercentage = async function () {
    const settings = await this.getSettings();
    return (settings.commissionRate * 100) || 15;
};

module.exports = mongoose.model('Settings', settingsSchema);
