/**
 * Debug script for Dashboard API
 * This will help identify any issues with the API endpoints
 */

import fetch from 'node-fetch';

const BASE_URL = 'http://localhost:3000/api/surveys/project';
const TREELOGY_ID = 1; // Replace with actual treelogy_id

async function testDashboardAPI() {
  console.log('🧪 Testing Dashboard API Debug...\n');

  try {
    // Test 1: Check if server is running
    console.log('1️⃣ Testing server connectivity...');
    const healthResponse = await fetch('http://localhost:3000/');
    console.log('Server status:', healthResponse.status);
    
    if (healthResponse.ok) {
      const healthText = await healthResponse.text();
      console.log('Server response:', healthText);
    }

    // Test 2: Test dashboard cards endpoint
    console.log('\n2️⃣ Testing Dashboard Cards API...');
    const cardsResponse = await fetch(`${BASE_URL}/${TREELOGY_ID}/dashboard/cards`, {
      headers: {
        'Authorization': 'Bearer test-token',
        'Content-Type': 'application/json'
      }
    });
    
    console.log('Cards API Status:', cardsResponse.status);
    console.log('Cards API Headers:', Object.fromEntries(cardsResponse.headers.entries()));
    
    if (cardsResponse.ok) {
      const cardsData = await cardsResponse.json();
      console.log('✅ Cards API Success:', JSON.stringify(cardsData, null, 2));
    } else {
      const errorText = await cardsResponse.text();
      console.log('❌ Cards API Error:', errorText);
    }

    // Test 3: Test condition chart endpoint
    console.log('\n3️⃣ Testing Condition Chart API...');
    const conditionResponse = await fetch(`${BASE_URL}/${TREELOGY_ID}/dashboard/charts/condition`, {
      headers: {
        'Authorization': 'Bearer test-token',
        'Content-Type': 'application/json'
      }
    });
    
    console.log('Condition Chart Status:', conditionResponse.status);
    
    if (conditionResponse.ok) {
      const conditionData = await conditionResponse.json();
      console.log('✅ Condition Chart Success:', JSON.stringify(conditionData, null, 2));
    } else {
      const errorText = await conditionResponse.text();
      console.log('❌ Condition Chart Error:', errorText);
    }

    // Test 4: Test all chart endpoints
    console.log('\n4️⃣ Testing All Chart Endpoints...');
    const chartEndpoints = [
      'charts/condition',
      'charts/ownership', 
      'charts/species',
      'charts/economic-importance',
      'charts/remarks'
    ];

    for (const endpoint of chartEndpoints) {
      try {
        const response = await fetch(`${BASE_URL}/${TREELOGY_ID}/dashboard/${endpoint}`, {
          headers: {
            'Authorization': 'Bearer test-token',
            'Content-Type': 'application/json'
          }
        });
        
        console.log(`${endpoint}: ${response.status} ${response.ok ? '✅' : '❌'}`);
        
        if (response.ok) {
          const data = await response.json();
          console.log(`  Data: ${JSON.stringify(data.data?.slice(0, 2) || 'No data')}`);
        } else {
          const errorText = await response.text();
          console.log(`  Error: ${errorText.substring(0, 100)}...`);
        }
      } catch (error) {
        console.log(`${endpoint}: ❌ Exception: ${error.message}`);
      }
    }

  } catch (error) {
    console.error('💥 Error testing API:', error.message);
  }

  console.log('\n🏁 Dashboard API debug completed!');
}

// Run the test
testDashboardAPI().catch(console.error);
