import { NextRequest, NextResponse } from 'next/server';
import { checkRateLimit, getClientIP, createRateLimitResponse } from '@/lib/rate-limit';

// Cache to store logo URLs (in production, use Redis or database)
const logoCache = new Map<string, { logoUrl: string | null; source: string; timestamp: number }>();
const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours

interface LogoResponse {
  logoUrl: string | null;
  source: 'clearbit' | 'google' | 'none';
}

// Rate limit: 30 requests per 15 minutes per IP
const LOGO_RATE_LIMIT = 30;
const LOGO_WINDOW_MS = 15 * 60 * 1000;

async function checkLogoExists(url: string): Promise<boolean> {
  try {
    const response = await fetch(url, {
      method: 'HEAD',
      headers: {
        'User-Agent': 'RateRight/1.0',
      },
    });
    return response.ok;
  } catch {
    return false;
  }
}

export async function GET(request: NextRequest) {
  try {
    // --- Rate limiting ---
    const clientIP = getClientIP(request);
    const rateLimit = checkRateLimit(`company-logo:${clientIP}`, LOGO_RATE_LIMIT, LOGO_WINDOW_MS);
    
    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }
    
    const searchParams = request.nextUrl.searchParams;
    const domain = searchParams.get('domain');

    if (!domain) {
      return NextResponse.json<LogoResponse>(
        { logoUrl: null, source: 'none' },
        { status: 400, headers: getCORSHeaders(request) }
      );
    }

    // Clean the domain (remove protocol if present)
    const cleanDomain = domain.replace(/^https?:\/\//, '').replace(/\/.*$/, '');
    
    // Check cache first
    const cacheKey = cleanDomain;
    const cached = logoCache.get(cacheKey);
    if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
      return NextResponse.json<LogoResponse>({
        logoUrl: cached.logoUrl,
        source: cached.source as LogoResponse['source'],
      }, {
        headers: getCORSHeaders(request),
      });
    }

    // Try Clearbit Logo API first
    const clearbitUrl = `https://logo.clearbit.com/${cleanDomain}`;
    const clearbitExists = await checkLogoExists(clearbitUrl);
    
    if (clearbitExists) {
      logoCache.set(cacheKey, {
        logoUrl: clearbitUrl,
        source: 'clearbit',
        timestamp: Date.now(),
      });
      
      return NextResponse.json<LogoResponse>({
        logoUrl: clearbitUrl,
        source: 'clearbit',
      }, {
        headers: getCORSHeaders(request),
      });
    }

    // Try Google Favicon as fallback
    const googleUrl = `https://www.google.com/s2/favicons?domain=${cleanDomain}&sz=128`;
    const googleExists = await checkLogoExists(googleUrl);
    
    if (googleExists) {
      logoCache.set(cacheKey, {
        logoUrl: googleUrl,
        source: 'google',
        timestamp: Date.now(),
      });
      
      return NextResponse.json<LogoResponse>({
        logoUrl: googleUrl,
        source: 'google',
      }, {
        headers: getCORSHeaders(request),
      });
    }

    // No logo found
    logoCache.set(cacheKey, {
      logoUrl: null,
      source: 'none',
      timestamp: Date.now(),
    });

    return NextResponse.json<LogoResponse>({
      logoUrl: null,
      source: 'none',
    }, {
      headers: getCORSHeaders(request),
    });

  } catch (error) {
    console.error('Logo fetch error:', error);
    
    return NextResponse.json<LogoResponse>(
      { logoUrl: null, source: 'none' },
      { status: 500, headers: getCORSHeaders(request) }
    );
  }
}

// CORS configuration - restrict to known origins
const ALLOWED_ORIGINS = [
  process.env.NEXT_PUBLIC_APP_URL, // Production URL from env
  'http://localhost:3000',         // Local development
  'https://localhost:3000',        // Local development with HTTPS
].filter(Boolean) as string[];

function getCORSHeaders(request: NextRequest): Record<string, string> {
  const origin = request.headers.get('origin');
  
  // Only allow specific origins, no wildcards (H5 fix)
  const allowedOrigin = origin && ALLOWED_ORIGINS.includes(origin) 
    ? origin 
    : ALLOWED_ORIGINS[0] || 'null';
  
  return {
    'Access-Control-Allow-Origin': allowedOrigin,
    'Access-Control-Allow-Methods': 'GET, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Vary': 'Origin',
  };
}

// Add OPTIONS handler for CORS
export async function OPTIONS(request: NextRequest) {
  return new NextResponse(null, {
    status: 200,
    headers: getCORSHeaders(request),
  });
}