/**
 * Reachable-area isochrones from MapMap's hosted engine (`POST /isochrone`).
 * "Where can I get to in N minutes?" — returns GeoJSON polygons for the
 * given contour times, ready to drop on a MapLibre fill layer.
 */
import type {
  LatLng,
  RouteProfile,
} from "../../modules/mapmap-react-native/src/MapmapNav.types";

const API_HOST = "https://api.mapmap.ai";

const PROFILE_TO_COSTING: Record<RouteProfile, string> = {
  car: "auto",
  bicycle: "bicycle",
  walking: "pedestrian",
  truck: "truck",
};

export type IsochroneContour = {
  minutes: number;
  /** Feature collection colour band (added to each feature's properties). */
  color: string;
};

export async function fetchIsochrone(
  apiKey: string,
  center: LatLng,
  profile: RouteProfile,
  contours: IsochroneContour[]
): Promise<GeoJSON.FeatureCollection | null> {
  if (!apiKey) return null;
  try {
    const res = await fetch(`${API_HOST}/isochrone`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        costing: PROFILE_TO_COSTING[profile],
        locations: [{ lat: center.latitude, lon: center.longitude }],
        contours: contours.map((c) => ({ time: c.minutes })),
        polygons: true,
      }),
    });
    if (!res.ok) return null;
    const body = (await res.json()) as GeoJSON.FeatureCollection;
    if (body.type !== "FeatureCollection") return null;
    // Tag each feature with our colour band (largest contour drawn first).
    body.features.forEach((f, i) => {
      const c = contours[i] ?? contours[contours.length - 1];
      f.properties = { ...(f.properties ?? {}), mmColor: c.color, mmMinutes: c.minutes };
    });
    return body;
  } catch {
    return null;
  }
}
