import re


def distance_to_nearest(
    poi_type = 'restaurant',
    department = 'bogot_dc',
    project = 'immap-colombia-270609', 
    dataset = 'wash_prep', 
    origin = 'grid_1x1km_wadmin', 
    destination = 'wash_pois_osm', 
    origin_id = 'id', 
    poi_id = 'osm_id', 
    km_dist = 20
):
    """
    Creates BQ query that finds distance nearest to a table of pois (destination)
    
    Returns
        (str): query calculating distance to nearest
    """
    query = f"""WITH all_dists AS (
                WITH destination AS (
                    SELECT
                    {poi_id},
                    geometry
                    FROM
                    `{dataset}.{destination}`
                    where fclass = '{poi_type}')
                SELECT
                    {origin_id},
                    origin.geometry,
                    ST_DISTANCE(st_centroid(st_geogfromtext(origin.geometry)), destination.geometry) AS dist
                FROM
                    (select * from `{dataset}.{origin}` where adm1_name = '{department}') AS origin,
                    destination
                WHERE
                    ST_DWITHIN(st_centroid(st_geogfromtext(origin.geometry)), destination.geometry, {km_dist}*1000))
                SELECT
                ARRAY_AGG(all_dists
                    ORDER BY
                    dist
                    LIMIT
                    1)[OFFSET(0)]
                FROM
                all_dists
                GROUP BY
                {origin_id}
            """
    
    return re.sub('[ ]+', ' ', query).replace('\n', ' ')