/**
 * Test Script for Enhanced SOTD Selection Logic
 * 
 * This script helps verify the new Site of the Day selection mechanism.
 * 
 * Usage:
 *   node test-sotd-selection.js
 */

import fetch from 'node-fetch';

const API_URL = process.env.API_URL || 'http://localhost:5000';

async function testSOTDSelection() {
  console.log('🧪 Testing Enhanced SOTD Selection Logic\n');
  console.log('═══════════════════════════════════════\n');

  try {
    // Test 1: Trigger manual SOTD selection
    console.log('Test 1: Manual SOTD Selection');
    console.log('─────────────────────────────────────');
    
    const selectResponse = await fetch(`${API_URL}/api/awards/sotd/select`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    });
    
    const selectData = await selectResponse.json();
    console.log('✅ Selection Result:', JSON.stringify(selectData, null, 2));
    console.log('\n');

    // Test 2: Get current SOTD state
    console.log('Test 2: Get SOTD State');
    console.log('─────────────────────────────────────');
    
    const stateResponse = await fetch(`${API_URL}/api/awards/sotd/state`);
    const stateData = await stateResponse.json();
    
    console.log('Current State:');
    console.log('  Website ID:', stateData.state?.currentWebsiteId);
    console.log('  Selection Date:', stateData.state?.lastSelectionDate);
    console.log('  Selection Reason:', stateData.state?.lastUpdateReason);
    console.log('  Pending Candidates:', stateData.state?.pendingCandidatesCount);
    console.log('  Recently Shown:', stateData.state?.recentlyShownCount);
    console.log('\nStatistics:');
    console.log('  From Votes:', stateData.state?.statistics?.totalSelectionsFromVotes);
    console.log('  From Pending:', stateData.state?.statistics?.totalSelectionsFromPending);
    console.log('  Fallback:', stateData.state?.statistics?.totalFallbackSelections);
    console.log('  Last Cron Run:', stateData.state?.statistics?.lastCronRunDate);
    console.log('\n');

    // Test 3: Get current SOTD for homepage
    console.log('Test 3: Get Homepage SOTD');
    console.log('─────────────────────────────────────');
    
    const sotdResponse = await fetch(`${API_URL}/api/awards/sotd`);
    const sotdData = await sotdResponse.json();
    
    if (sotdData.data) {
      console.log('Current SOTD:');
      console.log('  Website:', sotdData.data.websiteId?.Title);
      console.log('  Award ID:', sotdData.data._id);
      console.log('  URL:', sotdData.data.websiteId?.URL);
      console.log('\nMetadata:');
      console.log('  Selection Reason:', sotdData.metadata?.selectionReason);
      console.log('  Selection Date:', sotdData.metadata?.lastSelectionDate);
      console.log('  Pending Count:', sotdData.metadata?.pendingCandidatesCount);
    } else {
      console.log('⚠️ No SOTD data available');
    }
    console.log('\n');

    // Test 4: Wait and check if selection changes (for 5-minute cron)
    console.log('Test 4: Monitoring Cron Job (5-minute intervals)');
    console.log('─────────────────────────────────────');
    console.log('⏰ Cron job runs every 5 minutes');
    console.log('💡 Keep this script running to observe changes');
    console.log('   Or check back in 5 minutes to see if SOTD changed\n');
    
    console.log('═══════════════════════════════════════\n');
    console.log('✅ All tests completed!\n');
    console.log('📝 Next Steps:');
    console.log('   1. Monitor the backend console for cron logs');
    console.log('   2. Wait 5 minutes and run this test again');
    console.log('   3. Vote on websites to test vote-based selection');
    console.log('   4. When testing is done, update cronJobs.js:');
    console.log('      Change "*/5 * * * *" to "0 0 * * *" (midnight)');
    console.log('      Change time window from 5 minutes to 24 hours\n');

  } catch (error) {
    console.error('❌ Test failed:', error.message);
    console.error('\n⚠️ Make sure:');
    console.error('   - Backend server is running');
    console.error('   - MongoDB is connected');
    console.error('   - API_URL is correct (currently:', API_URL + ')');
  }
}

// Run the tests
testSOTDSelection();
