const mongoose = require('mongoose');
require('dotenv').config(); // Load environment variables
const User = require('./models/User');
const Order = require('./models/Order');
const Message = require('./models/Message');

// Connect to DB using the hardcoded string from config/db.js to ensure connection
// mongodb+srv://diaakardmash_db_user:t575rwL8lfCvGxRT@wassili-db.ty4o3dv.mongodb.net/?appName=wassili-db
const mongoURI = 'mongodb+srv://diaakardmash_db_user:t575rwL8lfCvGxRT@wassili-db.ty4o3dv.mongodb.net/?appName=wassili-db';
console.log('🔌 Connecting to MongoDB...', mongoURI.substring(0, 20) + '...');

async function debugChat() {
    try {
        await mongoose.connect(mongoURI);
        console.log('✅ Connected to MongoDB');

        // 1. Find the most recent message
        const lastMsg = await Message.findOne().sort({ createdAt: -1 });
        if (!lastMsg) {
            console.log('❌ No messages found in DB');
            return;
        }

        console.log('🔍 Last Message Found:', JSON.stringify(lastMsg, null, 2));
        console.log('   - ID Type:', typeof lastMsg._id);
        console.log('   - Order ID:', lastMsg.order);
        console.log('   - Order ID Type:', typeof lastMsg.order);
        console.log('   - Is Order ID an ObjectId?', lastMsg.order instanceof mongoose.Types.ObjectId);

        // 2. Check if we can find this message using the order ID string
        const orderIdString = lastMsg.order.toString();
        const countByString = await Message.countDocuments({ order: orderIdString });
        console.log(`🔎 Find by String ID (${orderIdString}): ${countByString} messages`);

        // 3. Check if we can find this message using ObjectId
        const countByObjectId = await Message.countDocuments({ order: lastMsg.order });
        console.log(`🔎 Find by ObjectId: ${countByObjectId} messages`);

        // 4. Check the Order itself
        const order = await Order.findById(lastMsg.order);
        if (order) {
            console.log('✅ Order exists in DB');
            console.log('   - Order Client:', order.client);
            console.log('   - Order Captain:', order.captain);
        } else {
            console.error('❌ Order NOT found in DB (Orphaned Message)');
        }

    } catch (err) {
        console.error('❌ Error:', err);
    } finally {
        await mongoose.disconnect();
    }
}

debugChat();
