/**
 * GET /api/servers - Server list with filtering handler
 */

import type { Env } from '../types';
import { jsonResponse } from '../utils';
import { AnvilServerRepository } from '../repositories/AnvilServerRepository';

/**
 * GET /api/servers - Server list with filtering
 * Uses anvil_* tables for pricing data
 */
export async function handleGetServers(
  request: Request,
  env: Env,
  corsHeaders: Record<string, string>
): Promise<Response> {
  try {
    const url = new URL(request.url);
    const minCpu = url.searchParams.get('minCpu');
    const minMemory = url.searchParams.get('minMemory');
    const region = url.searchParams.get('region');

    console.log('[GetServers] Query params:', {
      minCpu,
      minMemory,
      region,
    });

    // Generate cache key from query parameters
    const cacheKey = `servers:${url.search || 'all'}`;

    // Check cache first
    if (env.CACHE) {
      const cached = await env.CACHE.get(cacheKey);
      if (cached) {
        console.log('[GetServers] Cache hit for:', cacheKey);
        return jsonResponse({ ...JSON.parse(cached), cached: true }, 200, corsHeaders);
      }
    }

    // Validate and parse parameters
    let parsedCpu: number | undefined;
    let parsedMemory: number | undefined;

    if (minCpu) {
      parsedCpu = parseInt(minCpu, 10);
      if (isNaN(parsedCpu)) {
        return jsonResponse({ error: 'Invalid minCpu parameter' }, 400, corsHeaders);
      }
    }

    if (minMemory) {
      parsedMemory = parseInt(minMemory, 10);
      if (isNaN(parsedMemory)) {
        return jsonResponse({ error: 'Invalid minMemory parameter' }, 400, corsHeaders);
      }
    }

    // Use repository to fetch servers
    const repository = new AnvilServerRepository(env.DB);
    const servers = await repository.findServers({
      minCpu: parsedCpu,
      minMemoryGb: parsedMemory,
      region: region ? [region] : undefined,
      limit: 100,
    });

    console.log('[GetServers] Found servers:', servers.length);

    const responseData = {
      servers,
      count: servers.length,
      filters: { minCpu, minMemory, region },
    };

    // Cache successful results (only if we have servers)
    if (env.CACHE && servers.length > 0) {
      await env.CACHE.put(cacheKey, JSON.stringify(responseData), {
        expirationTtl: 300, // 5 minutes
      });
    }

    return jsonResponse(responseData, 200, corsHeaders);
  } catch (error) {
    console.error('[GetServers] Error:', error);
    const requestId = crypto.randomUUID();
    return jsonResponse(
      {
        error: 'Failed to retrieve servers',
        request_id: requestId,
      },
      500,
      corsHeaders
    );
  }
}
