const express = require('express');

// Test the route order fix
console.log('🧪 Testing Route Order Fix...\n');

// Create a mock router to test route matching
const router = express.Router();

// Mock controllers
const mockControllers = {
    demoJoinGroup: (req, res) => {
        console.log('✅ DEMO JOIN GROUP called - Route order is CORRECT!');
        res.json({ success: true, message: 'Demo join group called' });
    },
    joinGroup: (req, res) => {
        console.log('❌ REGULAR JOIN GROUP called - Route order is WRONG!');
        console.log('groupId parameter:', req.params.groupId);
        res.json({ success: false, message: 'Wrong route called' });
    }
};

// Add routes in the CORRECT order (specific routes first)
router.post('/demo/join', mockControllers.demoJoinGroup);
router.post('/:groupId/join', mockControllers.joinGroup);

// Test the route matching
const testUrl = '/demo/join';
const testMethod = 'POST';

console.log(`🔍 Testing URL: ${testUrl} with method: ${testMethod}\n`);

// Simulate Express route matching
const routes = router.stack;
let matchedRoute = null;

for (let i = 0; i < routes.length; i++) {
    const route = routes[i];
    if (route.route && route.route.methods[testMethod.toLowerCase()]) {
        const routePath = route.route.path;
        console.log(`📋 Checking route ${i + 1}: ${testMethod} ${routePath}`);
        
        // Simple path matching (Express uses more complex regex)
        if (routePath === testUrl) {
            matchedRoute = route;
            console.log(`✅ EXACT MATCH found: ${routePath}`);
            break;
        } else if (routePath.includes(':')) {
            console.log(`🔄 PARAMETER ROUTE: ${routePath} (would match /demo/join as groupId="demo")`);
        }
    }
}

console.log('\n📊 Route Order Analysis:');
console.log('1. POST /demo/join - SPECIFIC ROUTE (should match first)');
console.log('2. POST /:groupId/join - PARAMETER ROUTE (should match second)');

console.log('\n🎯 Conclusion:');
if (matchedRoute && matchedRoute.route.path === '/demo/join') {
    console.log('✅ Route order is CORRECT! /demo/join will be matched before /:groupId/join');
    console.log('✅ The fix should resolve the "Cast to ObjectId failed for value \"demo\"" error');
} else {
    console.log('❌ Route order is WRONG! /:groupId/join would match first');
    console.log('❌ This would cause "demo" to be treated as a groupId parameter');
}

console.log('\n🔧 The fix applied:');
console.log('- Moved POST /demo/join BEFORE POST /:groupId/join in routes/groupRoutes.js');
console.log('- This ensures specific routes are matched before parameter routes');
console.log('- Express will now correctly route /demo/join to demoJoinGroup function');