use axum::http::StatusCode;

/// Compute the lat/lon bounding box of an H3 cell, with a configurable buffer in degrees.
pub fn h3_cell_bounds(cell: h3o::CellIndex, buffer: f64) -> (f64, f64, f64, f64) {
    let boundary = cell.boundary();
    let (mut min_lat, mut max_lat) = (f64::INFINITY, f64::NEG_INFINITY);
    let (mut min_lon, mut max_lon) = (f64::INFINITY, f64::NEG_INFINITY);
    for vertex in boundary.iter() {
        let lat = vertex.lat();
        let lon = vertex.lng();
        if lat < min_lat {
            min_lat = lat;
        }
        if lat > max_lat {
            max_lat = lat;
        }
        if lon < min_lon {
            min_lon = lon;
        }
        if lon > max_lon {
            max_lon = lon;
        }
    }
    (
        min_lat - buffer,
        min_lon - buffer,
        max_lat + buffer,
        max_lon + buffer,
    )
}

pub fn parse_bounds(bounds_str: &str) -> Result<(f64, f64, f64, f64), (StatusCode, String)> {
    let parts: Vec<f64> = bounds_str
        .split(',')
        .map(|part| part.trim().parse::<f64>())
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| {
            (
                StatusCode::BAD_REQUEST,
                "Invalid bounds format. Use: south,west,north,east".into(),
            )
        })?;

    if parts.len() != 4 {
        return Err((
            StatusCode::BAD_REQUEST,
            "Invalid bounds format. Use: south,west,north,east".into(),
        ));
    }

    Ok((parts[0], parts[1], parts[2], parts[3]))
}
