import type { APIRoute } from 'astro';
import { runFirebaseEventScraper, initializeScraperOrganization } from '../../../lib/firebaseEventScraper';
import { logAPIRequest, logSecurityEvent } from '../../../lib/logger';
import { checkRateLimit } from '../../../lib/auth';

export const POST: APIRoute = async ({ request }) => {
  const startTime = Date.now();
  const clientIP = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
  const userAgent = request.headers.get('user-agent') || 'unknown';
  
  try {
    // Rate limiting - only 50 requests per hour per IP (increased for testing)
    if (!checkRateLimit(clientIP, 50, 3600000)) {
      logSecurityEvent({
        type: 'rate_limit',
        ipAddress: clientIP,
        userAgent,
        severity: 'medium',
        details: { endpoint: '/api/admin/scraper', limit: 5 }
      });

      return new Response(JSON.stringify({ 
        error: 'Rate limit exceeded. Please try again later.' 
      }), {
        status: 429,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Parse request body for action
    const body = await request.json().catch(() => ({ action: 'run' }));
    const action = body.action || 'run';

    let result;
    
    switch (action) {
      case 'init': {
        // Initialize scraper organization
        const initialized = await initializeScraperOrganization();
        result = {
          success: initialized,
          message: initialized ? 'Scraper organization initialized' : 'Failed to initialize scraper organization'
        };
        break;
      }
        
      case 'run':
      default: {
        // Run the Firebase scraper
        result = await runFirebaseEventScraper();
        break;
      }
    }

    const responseTime = Date.now() - startTime;

    // Log API request
    logAPIRequest({
      method: 'POST',
      url: '/api/admin/scraper',
      statusCode: 200,
      responseTime,
      ipAddress: clientIP,
      userAgent
    });

    return new Response(JSON.stringify(result), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      }
    });

  } catch (error) {
    const responseTime = Date.now() - startTime;
    
    logAPIRequest({
      method: 'POST',
      url: '/api/admin/scraper',
      statusCode: 500,
      responseTime,
      ipAddress: clientIP,
      userAgent
    });

    logSecurityEvent({
      type: 'api_error',
      ipAddress: clientIP,
      userAgent,
      severity: 'high',
      details: { 
        endpoint: '/api/admin/scraper', 
        error: error instanceof Error ? error.message : 'Unknown error' 
      }
    });

    return new Response(JSON.stringify({
      success: false,
      message: 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

export const GET: APIRoute = async ({ request, url }) => {
  const startTime = Date.now();
  const clientIP = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || 'unknown';
  const userAgent = request.headers.get('user-agent') || 'unknown';
  
  try {
    // Rate limiting - only 10 requests per hour per IP for status checks
    if (!checkRateLimit(clientIP, 10, 3600000)) {
      return new Response(JSON.stringify({ 
        error: 'Rate limit exceeded. Please try again later.' 
      }), {
        status: 429,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Return scraper status
    const responseTime = Date.now() - startTime;

    logAPIRequest({
      method: 'GET',
      url: '/api/admin/scraper',
      statusCode: 200,
      responseTime,
      ipAddress: clientIP,
      userAgent
    });

    return new Response(JSON.stringify({
      success: true,
      message: 'Event scraper is operational',
      endpoints: {
        run: 'POST /api/admin/scraper with {"action": "run"}',
        init: 'POST /api/admin/scraper with {"action": "init"}',
        status: 'GET /api/admin/scraper'
      },
      rateLimit: '5 requests per hour for POST, 10 for GET'
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      }
    });

  } catch (error) {
    console.error('Error in scraper GET endpoint:', error);
    return new Response(JSON.stringify({
      success: false,
      message: 'Internal server error'
    }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};