import { NextResponse } from 'next/server';

const PLAN_BASE_URL = 'https://stats.biohazardvfx.com';
const SERVER_NAME = 'BiohazardVFX';

interface PlanPlayerData {
  name: string; // HTML string with <a> tag, need to extract text
  activePlaytime?: {
    d: string; // Display format like "10d 3h 46m 48s"
    v: string; // Value in milliseconds as string
  };
  sessions?: string;
  [key: string]: unknown;
}

interface PlanPlayersResponse {
  data?: PlanPlayerData[];
  [key: string]: unknown;
}

// Extract player name from HTML string
function extractPlayerName(nameString: string): string {
  // Name format: '<a class="link" href="../player/...">PlayerName</a>'
  const match = nameString.match(/>(.+?)<\/a>/);
  return match ? match[1] : nameString.replace(/<[^>]*>/g, '');
}

export async function GET() {
  try {
    const playersResponse = await fetch(
      `${PLAN_BASE_URL}/v1/players?server=${SERVER_NAME}`,
      {
        headers: {
          'Accept': 'application/json',
          'User-Agent': 'Mozilla/5.0 (compatible; BiohazardVFX/1.0)',
          'Referer': PLAN_BASE_URL,
        },
        cf: {
          cacheTtl: 300,
          cacheEverything: true,
        }
      }
    );

    if (!playersResponse.ok) {
      throw new Error(`Plan API returned ${playersResponse.status}`);
    }

    const data: PlanPlayersResponse = await playersResponse.json();
    
    if (!data.data || !Array.isArray(data.data)) {
      return NextResponse.json({
        players: [],
        total: 0,
        message: 'No player data available',
      });
    }

    // Process and sort players by playtime
    const processedPlayers = data.data
      .map((player) => {
        const playtimeMs = player.activePlaytime?.v 
          ? parseInt(player.activePlaytime.v, 10) 
          : 0;
        
        // Convert milliseconds to seconds
        const playtimeSeconds = Math.floor(playtimeMs / 1000);
        
        // Format playtime for display
        const days = Math.floor(playtimeSeconds / 86400);
        const hours = Math.floor((playtimeSeconds % 86400) / 3600);
        const minutes = Math.floor((playtimeSeconds % 3600) / 60);
        
        let formatted = '';
        if (days > 0) {
          formatted = `${days}d ${hours}h`;
        } else if (hours > 0) {
          formatted = `${hours}h ${minutes}m`;
        } else {
          formatted = `${minutes}m`;
        }

        return {
          name: extractPlayerName(player.name),
          playtime: playtimeSeconds,
          playtimeFormatted: player.activePlaytime?.d || formatted,
          sessions: parseInt(player.sessions || '0', 10),
        };
      })
      .filter((player) => player.playtime > 0) // Only players with playtime
      .sort((a, b) => b.playtime - a.playtime) // Sort descending by playtime
      .slice(0, 20); // Top 20 players

    return NextResponse.json({
      players: processedPlayers,
      total: processedPlayers.length,
    });
  } catch (error) {
    console.error('Error fetching Plan leaderboard:', error);
    return NextResponse.json(
      {
        error: 'Failed to fetch leaderboard data',
        players: [],
        total: 0,
      },
      { status: 500 }
    );
  }
}

