import { NextResponse } from 'next/server';

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

interface PlanServerOverview {
  numbers?: {
    online_players?: number;
    current_uptime?: number;
    total_players?: number;
    sessions?: number;
    regular_players?: number;
  };
  last_7_days?: {
    unique_players?: number;
    unique_players_day?: number;
    average_tps?: string;
  };
  [key: string]: unknown;
}

export async function GET() {
  try {
    // Fetch server overview data (includes uptime)
    const overviewResponse = await fetch(
      `${PLAN_BASE_URL}/v1/serverOverview?server=${SERVER_NAME}`,
      {
        headers: {
          'Accept': 'application/json',
          'User-Agent': 'Mozilla/5.0 (compatible; BiohazardVFX/1.0)',
          'Referer': PLAN_BASE_URL,
        },
        cf: {
          cacheTtl: 30,
          cacheEverything: true,
        }
      }
    );

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

    const overviewData: PlanServerOverview = await overviewResponse.json();

    // Extract uptime (Plan provides it in milliseconds in numbers.current_uptime)
    const uptimeMs = overviewData.numbers?.current_uptime || 0;
    const uptimeSeconds = Math.floor(uptimeMs / 1000);

    // Calculate days, hours, minutes
    const days = Math.floor(uptimeSeconds / 86400);
    const hours = Math.floor((uptimeSeconds % 86400) / 3600);
    const minutes = Math.floor((uptimeSeconds % 3600) / 60);

    return NextResponse.json({
      online: true,
      players: {
        online: overviewData.numbers?.online_players || 0,
        // Note: Plan doesn't provide a real-time list of online player names via JSON API
        // Only available through websockets or by parsing the HTML
        playerList: [],
      },
      uptime: {
        days,
        hours,
        minutes,
        formatted: days > 0 ? `${days}d ${hours}h ${minutes}m` : `${hours}h ${minutes}m`,
      },
      stats: {
        totalPlayers: overviewData.numbers?.total_players || 0,
        uniquePlayers7d: overviewData.last_7_days?.unique_players || 0,
        averageTps: overviewData.last_7_days?.average_tps || 'N/A',
      }
    });
  } catch (error) {
    console.error('Error fetching Plan server status:', error);
    return NextResponse.json(
      {
        error: 'Failed to fetch server status',
        online: false,
        players: { online: 0, playerList: [] },
        uptime: null
      },
      { status: 500 }
    );
  }
}
