import { NextResponse } from 'next/server';
import { Connection } from '@solana/web3.js';

const RPC_URLS = (process.env.SOLANA_RPC_URLS || '').split(',').filter(url => url.trim());

export async function GET() {
  try {
    const rpcStatuses = [];
    
    for (const rpcUrl of RPC_URLS) {
      const trimmedUrl = rpcUrl.trim();
      let status = {
        url: trimmedUrl,
        status: 'unknown',
        latency: null,
        error: null
      };
      
      try {
        const startTime = Date.now();
        const connection = new Connection(trimmedUrl);
        
        // Test basic connection with getVersion
        await connection.getVersion();
        
        const latency = Date.now() - startTime;
        status.status = 'healthy';
        status.latency = latency;
        
      } catch (error) {
        status.status = 'failed';
        status.error = error.message;
      }
      
      rpcStatuses.push(status);
    }
    
    const healthyCount = rpcStatuses.filter(s => s.status === 'healthy').length;
    const totalCount = rpcStatuses.length;
    
    return NextResponse.json({
      success: true,
      summary: {
        healthy: healthyCount,
        total: totalCount,
        healthyPercentage: totalCount > 0 ? Math.round((healthyCount / totalCount) * 100) : 0
      },
      endpoints: rpcStatuses,
      timestamp: new Date().toISOString()
    });
    
  } catch (error) {
    console.error('RPC Status Check Error:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to check RPC status',
        details: error.message,
        timestamp: new Date().toISOString()
      },
      { status: 500 }
    );
  }
}
