import type { APIRoute } from 'astro';
import { geolocationService } from '../../../lib/geolocation';

export const GET: APIRoute = async ({ request, url }) => {
  try {
    const searchParams = new URL(request.url).searchParams;
    const userId = searchParams.get('userId');
    const sessionId = searchParams.get('sessionId');
    
    if (!userId && !sessionId) {
      return new Response(JSON.stringify({
        success: false,
        error: 'userId or sessionId is required'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    const preferences = await geolocationService.getUserLocationPreference(userId || undefined, sessionId || undefined);
    
    return new Response(JSON.stringify({
      success: true,
      data: preferences
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  } catch (error) {

    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to get location preferences'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const {
      userId,
      sessionId,
      preferredLatitude,
      preferredLongitude,
      preferredCity,
      preferredState,
      preferredCountry,
      preferredZipCode,
      searchRadiusMiles,
      locationSource
    } = body;
    
    if (!sessionId) {
      return new Response(JSON.stringify({
        success: false,
        error: 'sessionId is required'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    if (!preferredLatitude || !preferredLongitude) {
      return new Response(JSON.stringify({
        success: false,
        error: 'preferredLatitude and preferredLongitude are required'
      }), {
        status: 400,
        headers: {
          'Content-Type': 'application/json'
        }
      });
    }
    
    await geolocationService.saveUserLocationPreference({
      userId,
      sessionId,
      preferredLatitude,
      preferredLongitude,
      preferredCity,
      preferredState,
      preferredCountry,
      preferredZipCode,
      searchRadiusMiles: searchRadiusMiles || 50,
      locationSource: locationSource || 'manual'
    });
    
    return new Response(JSON.stringify({
      success: true,
      message: 'Location preferences saved successfully'
    }), {
      status: 200,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  } catch (error) {

    return new Response(JSON.stringify({
      success: false,
      error: 'Failed to save location preferences'
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
};