import { raw } from "../../../../packages/database/generated/client/runtime/library";

export const getOsmAddress = async (lat: number, lng: number) => {
	const address = await fetch(
		`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json`,
	);
	const data = (await address.json()) as {
		address?: {
			ISO3166_2_lvl4?: string;
			country?: string;
			country_code?: string;
			county?: string;
			house_number?: string;
			municipality?: string;
			postcode?: string;
			road?: string;
			state?: string;
			city?: string;
			town?: string;
		};
		display_name?: string;
		importance?: number;
		lat?: string;
		licence?: string;
		lon?: string;
		name?: string;
		osm_id?: number;
		osm_type?: string;
		place_id?: number;
		place_rank?: number;
		type?: string;
	};

	let addressStreet = "";
	if (!data.address?.road && !data.address?.house_number) {
		addressStreet = "keine Straße, keine HN";
	} else if (data.address?.road) {
		addressStreet += data.address.road;
	} else if (data.address?.house_number) {
		addressStreet += data.address.house_number;
	}

	return {
		raw: data,
		parsed: {
			addressCity: data.address?.city || data.address?.town || "",
			addressStreet,
			addressZip: data.address?.postcode || "",
		},
	};
};
