import { OSMWay } from "@repo/db";
import { centroid, distance } from "@turf/turf";

function toPolygonFeature(nodes: { lat: number; lon: number }[]) {
	if (!nodes || nodes.length < 3) return null;

	const coords = nodes.map((n) => [n.lon, n.lat]);
	const isClosed =
		coords.length >= 1 &&
		coords[0]![0] === coords[coords.length - 1]![0] &&
		coords[0]![1] === coords[coords.length - 1]![1];
	if (!isClosed) coords.push(coords[0]!); // Polygon schließen

	return {
		type: "Feature",
		geometry: {
			type: "Polygon",
			coordinates: [coords],
		},
		properties: {},
	};
}

// Hauptfunktion: findet das nächstgelegene Polygon zu einem Punkt
export function findClosestPolygon(
	ways: OSMWay[],
	referencePoint: {
		lat: number;
		lon: number;
	},
): OSMWay | null {
	let closest: OSMWay | null = null;
	let minDistance = Infinity;

	for (const way of ways) {
		const polygon = toPolygonFeature(way.nodes);
		if (!polygon) continue;

		const center = centroid(polygon as any).geometry.coordinates; // [lon, lat]

		const newDistance = distance([referencePoint.lon, referencePoint.lat], center);

		if (newDistance < minDistance) {
			minDistance = newDistance;
			closest = way;
		}
	}

	return closest;
}
