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

const ALLOWED_ORIGIN = process.env.NEXT_PUBLIC_APP_URL || 'https://rateright.com.au';

// 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';
}

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 limit by IP
    const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown';
    const rateLimit = checkRateLimit(ip);
    if (!rateLimit.allowed) {
      return NextResponse.json(
        { logoUrl: null, source: 'none' },
        { status: 429 }
      );
    }

    const searchParams = request.nextUrl.searchParams;
    const domain = searchParams.get('domain');

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

    // 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'],
      });
    }

    // 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',
      });
    }

    // 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',
      });
    }

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

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

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

// Add OPTIONS handler for CORS
export async function OPTIONS() {
  return new NextResponse(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
      'Access-Control-Allow-Methods': 'GET, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    },
  });
}