import { NextRequest, NextResponse } from "next/server";
import { fetchNearbyPlaces, fetchCityPlaces } from "@/lib/halal-places";

export const dynamic = "force-dynamic";
export const maxDuration = 30; // Overpass can be slow

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const q = searchParams.get("q")?.trim();
    const latParam = searchParams.get("lat");
    const lngParam = searchParams.get("lng");
    const city = searchParams.get("city")?.trim();
    const country = searchParams.get("country")?.trim();
    const type = searchParams.get("type")?.toLowerCase();
    const radiusParam = searchParams.get("radius");

    const radius = radiusParam ? parseInt(radiusParam, 10) : 5000;

    let places;
    let searchLocation: string | null = null;

    // Priority 1: City search (with optional country)
    if (city) {
      const result = await fetchCityPlaces(city, country || undefined, radius);
      places = result.places;
      searchLocation = result.location;
    }
    // Priority 2: Lat/lng nearby search
    else if (latParam && lngParam) {
      const lat = parseFloat(latParam);
      const lng = parseFloat(lngParam);
      if (!isNaN(lat) && !isNaN(lng)) {
        places = await fetchNearbyPlaces(lat, lng, radius);
        searchLocation = `${lat.toFixed(4)}, ${lng.toFixed(4)}`;
      } else {
        places = [];
      }
    }
    // Priority 3: Text search only (no location) — return empty, need a location
    else if (q) {
      // Text search without location — return empty with a helpful message
      return NextResponse.json({
        places: [],
        error: "Please enable location or specify a city",
        searchLocation: null,
      });
    }
    // No params at all — default to Kuala Lumpur as fallback
    else {
      const result = await fetchCityPlaces("Kuala Lumpur", "Malaysia", radius);
      places = result.places;
      searchLocation = result.location;
    }

    // Apply post-fetch filters
    if (type && ["mosque", "restaurant", "cafe"].includes(type)) {
      places = places.filter((p) => p.type === type);
    }

    if (q) {
      const lowerQ = q.toLowerCase();
      places = places.filter(
        (p) =>
          p.name.toLowerCase().includes(lowerQ) ||
          p.address.toLowerCase().includes(lowerQ)
      );
    }

    // Sort by distance if lat/lng provided
    if (latParam && lngParam) {
      const userLat = parseFloat(latParam);
      const userLng = parseFloat(lngParam);
      if (!isNaN(userLat) && !isNaN(userLng)) {
        places = places
          .map((p) => ({
            ...p,
            distance: haversineDistance(userLat, userLng, p.lat, p.lng),
          }))
          .sort((a, b) => (a.distance ?? Infinity) - (b.distance ?? Infinity));
      }
    }

    return NextResponse.json({
      places,
      searchLocation,
      total: places.length,
    });
  } catch (error) {
    console.error("GET /api/halal/places error:", error);
    return NextResponse.json(
      { places: [], error: "Unable to fetch halal places right now" },
      { status: 200 } // Return 200 with empty results — graceful degradation
    );
  }
}

// ─── Client-side haversine (duplicated for SSR-safety) ─────
function haversineDistance(
  lat1: number,
  lng1: number,
  lat2: number,
  lng2: number
): number {
  const R = 6371;
  const dLat = ((lat2 - lat1) * Math.PI) / 180;
  const dLng = ((lng2 - lng1) * Math.PI) / 180;
  const a =
    Math.sin(dLat / 2) ** 2 +
    Math.cos((lat1 * Math.PI) / 180) *
      Math.cos((lat2 * Math.PI) / 180) *
      Math.sin(dLng / 2) ** 2;
  return Math.round(R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) * 100) / 100;
}
