use crate::models::List;

use super::Source;

use async_trait::async_trait;

#[derive(Debug)]
pub struct HttpSource {
    url: String,
    lifetime: u64,
}

impl HttpSource {
    pub fn new(url: String, lifetime: u64) -> Self {
        Self { url, lifetime }
    }
}

#[async_trait]
impl Source for HttpSource {
    type Error = Error;

    async fn fetch(&self) -> Result<List, Error> {
        let client = reqwest::Client::new();
        client
            .get(&self.url)
            .send()
            .await
            .map_err(|err| {
                tracing::error!("error sending request: {err}");
                Error::Request
            })?
            .json()
            .await
            .map_err(|err| {
                tracing::error!("error deserializing response: {err}");
                Error::Deserialize
            })
    }

    fn lifetime(&self) -> u64 {
        self.lifetime
    }
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("failed to send request")]
    Request,

    #[error("could not deserialize response")]
    Deserialize,
}
