// src/app/api/geolocation/route.ts
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  try {
    // Get client IP address - in production, this would come from request headers
    const forwardedFor = request.headers.get('x-forwarded-for');
    const clientIP = forwardedFor ? forwardedFor.split(',')[0].trim() : '';
    
    // Make request to ipapi.co
    const apiUrl = clientIP ? `https://ipapi.co/${clientIP}/json/` : 'https://ipapi.co/json/';
    const response = await fetch(apiUrl, { 
      next: { revalidate: 86400 } // Cache for 24 hours
    });
    
    if (!response.ok) {
      throw new Error(`Error from ipapi.co: ${response.status}`);
    }
    
    const data = await response.json();
    
    return NextResponse.json({
      success: true,
      data: {
        ip: data.ip,
        country: data.country,
        country_name: data.country_name,
        country_code: data.country_code,
        continent_code: data.continent_code,
        city: data.city,
        region: data.region,
        postal: data.postal,
        latitude: data.latitude,
        longitude: data.longitude,
        timezone: data.timezone,
        currency: data.currency,
        currency_name: data.currency_name,
        languages: data.languages
      }
    });
  } catch (error) {
    console.error('Error fetching geolocation data:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to detect country', error: String(error) },
      { status: 500 }
    );
  }
}
