use time::{Duration, OffsetDateTime};
use crate::domain::{Region, TimeRange, WeatherForecast};
use crate::ports::WeatherRepository;
use super::ApplicationError;
pub struct GetWeather<W: WeatherRepository> {
weather: W,
}
impl<W: WeatherRepository> GetWeather<W> {
pub fn new(weather: W) -> Self {
Self { weather }
}
pub async fn latest(
&self,
reference: OffsetDateTime,
) -> Result<WeatherForecast, ApplicationError> {
let window = TimeRange::new(
reference - Duration::hours(3),
reference + Duration::hours(3),
)
.ok_or(ApplicationError::NotFound(Region::National))?;
self.weather
.weather_latest(window)
.await?
.into_iter()
.min_by_key(|f| (f.valid_at - reference).whole_seconds().abs())
.ok_or(ApplicationError::NotFound(Region::National))
}
pub async fn series(&self, valid: TimeRange) -> Result<Vec<WeatherForecast>, ApplicationError> {
Ok(self.weather.weather_latest(valid).await?)
}
}