import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
    const { searchParams } = new URL(request.url);
    const query = searchParams.get('q');
    if (!query || query.length < 2) {
        return NextResponse.json({ results: [] });
    }

    try {
        const res = await fetch(
            `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(query)}&count=5&language=en&format=json`
        );
        const data = await res.json();
        const results = (data.results || []).map((r: any) => ({
            name: r.name,
            country: r.country,
            admin1: r.admin1,
            lat: r.latitude,
            lon: r.longitude,
        }));
        return NextResponse.json({ results });
    } catch {
        return NextResponse.json({ results: [] });
    }
}
