import type { GeoPoint } from "../model/mapTypes";

export type BBox = {
  minLon: number;
  minLat: number;
  maxLon: number;
  maxLat: number;
};

export function bboxForPoints(points: GeoPoint[]): BBox {
  let minLon = Number.POSITIVE_INFINITY;
  let minLat = Number.POSITIVE_INFINITY;
  let maxLon = Number.NEGATIVE_INFINITY;
  let maxLat = Number.NEGATIVE_INFINITY;

  for (const point of points) {
    minLon = Math.min(minLon, point.lon);
    minLat = Math.min(minLat, point.lat);
    maxLon = Math.max(maxLon, point.lon);
    maxLat = Math.max(maxLat, point.lat);
  }

  return { minLon, minLat, maxLon, maxLat };
}

export function bboxContainsPoint(bbox: BBox, point: GeoPoint): boolean {
  return (
    point.lon >= bbox.minLon &&
    point.lon <= bbox.maxLon &&
    point.lat >= bbox.minLat &&
    point.lat <= bbox.maxLat
  );
}

export function bboxIntersects(a: BBox, b: BBox): boolean {
  return a.minLon <= b.maxLon && a.maxLon >= b.minLon && a.minLat <= b.maxLat && a.maxLat >= b.minLat;
}

