const mongoose = require('mongoose');

const OrderSchema = new mongoose.Schema(
    {
        client: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User',
            required: true,
        },
        captain: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User',
        },

        // 👇 التعديل الجذري: تفاصيل الاستلام 👇
        pickup: {
            address: { type: String, required: true },
            contactName: { type: String, required: true },
            contactPhone: { type: String, required: true },
            lat: { type: Number },
            lng: { type: Number }
        },

        dropoff: {
            address: { type: String, required: true },
            receiverName: { type: String, required: true },
            receiverPhone: { type: String, required: true },
            lat: { type: Number },
            lng: { type: Number }
        },

        details: { type: String },

        // 👇 السعر والمسافة 👇
        distanceType: {
            type: String,
            enum: ['short', 'medium', 'long', 'custom'], // قريب، وسط، بعيد، مخصص
            required: true
        },
        price: { type: Number, required: true }, // السعر الإجمالي
        appFee: { type: Number, default: 0 }, // نسبة التطبيق
        netRevenue: { type: Number, default: 0 }, // صافي ربح الكابتن

        parcelImage: { type: String }, // 📷 صورة الطرد (اختياري من العميل)
        proofOfPickupImage: { type: String }, // 📸 صورة إثبات الاستلام (إلزامية من الكابتن)


        status: {
            type: String,
            enum: ['pending', 'scheduled', 'accepted', 'picked_up', 'delivered', 'cancelled'],
            default: 'pending',
        },
        scheduledAt: { type: Date, default: null }, // ⏰ طلب مجدول
        location: {
            lat: { type: Number },
            lng: { type: Number }
        },
        rating: {
            score: { type: Number, min: 1, max: 10 },
            comment: { type: String }
        },
        isRated: { type: Boolean, default: false }, // Prevent repeated rating prompts
        complaint: {
            text: { type: String },
            status: { type: String, enum: ['none', 'pending', 'resolved'], default: 'none' },
            createdAt: { type: Date }
        },

        // 💬 Negotiation System — Multi-Offer (each captain can submit their own)
        negotiations: [{
            captainId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
            captainName: { type: String },
            proposedPrice: { type: Number },
            originalPrice: { type: Number },
            expiresAt: { type: Date },
            status: {
                type: String,
                enum: ['pending', 'accepted', 'rejected', 'expired', 'withdrawn'],
                default: 'pending'
            }
        }],

        // 💬 [Legacy] kept for backward compat — no longer locks the order
        negotiation: {
            isActive: { type: Boolean, default: false },
            captainId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
            proposedPrice: { type: Number },
            originalPrice: { type: Number },
            expiresAt: { type: Date },
            status: {
                type: String,
                enum: ['none', 'pending', 'accepted', 'rejected', 'expired'],
                default: 'none'
            }
        },

        // 🛒 Shop/Directory Order Fields
        orderType: {
            type: String,
            enum: ['delivery', 'shop'],
            default: 'delivery'
        },
        shopOrderId: { type: mongoose.Schema.Types.ObjectId, ref: 'ShopOrder' }, // 🔗 ربط بطلب المتجر الأصلي
        shopId: { type: mongoose.Schema.Types.ObjectId, ref: 'Place' },
        shopName: { type: String },
        shopPhone: { type: String },
        items: [{ type: String }], // list of requested item names / notes

        // 🧾 Pre-payment receipt (shop orders)
        shopOrderDetails: { type: String },      // تفاصيل الطلبية التي اتفق عليها مع المحل
        receiptImage: { type: String },          // صورة إشعار الدفع (base64 أو URL)
    },
    { timestamps: true }
);

// ✅ Adding Indexes for Performance
OrderSchema.index({ client: 1 });
OrderSchema.index({ captain: 1 });
OrderSchema.index({ status: 1 });
OrderSchema.index({ captain: 1, status: 1 }); // 🔒 Compound index for trips query
OrderSchema.index({ client: 1, createdAt: -1 }); // 🚀 PERFORMANCE: Queries for "My Orders"
OrderSchema.index({ status: 1, createdAt: -1 }); // 🚀 PERFORMANCE: Captain sorting pending orders
OrderSchema.index({ createdAt: -1 }); // For sorting by date
OrderSchema.index({ scheduledAt: 1, status: 1 }); // ⏰ For scheduled order cron job

// 🔄 Sync Order status back to ShopOrder
OrderSchema.post('save', async function(doc) {
    if (doc.shopOrderId) {
        try {
            const ShopOrder = mongoose.model('ShopOrder');
            const shopOrder = await ShopOrder.findById(doc.shopOrderId);
            if (shopOrder) {
                let changed = false;
                if (doc.status === 'accepted' && shopOrder.status !== 'captain_assigned') {
                    shopOrder.status = 'captain_assigned';
                    shopOrder.captain = doc.captain;
                    changed = true;
                } else if (doc.status === 'picked_up' && shopOrder.status !== 'picked_up') {
                    shopOrder.status = 'picked_up';
                    changed = true;
                } else if (doc.status === 'delivered' && shopOrder.status !== 'delivered') {
                    shopOrder.status = 'delivered';
                    shopOrder.deliveredAt = new Date();
                    changed = true;
                } else if (doc.status === 'cancelled' && shopOrder.status !== 'cancelled') {
                    shopOrder.status = 'cancelled';
                    changed = true;
                }
                
                if (changed) {
                    await shopOrder.save();
                }
            }
        } catch (err) {
            console.error('Error syncing Order to ShopOrder:', err);
        }
    }
});

module.exports = mongoose.model('Order', OrderSchema);