use tokio::time::Instant;

use super::{DataCommitRequest, DataLoadRequest};

pub trait LoadFromUpstream<Key: Send, Data: ServiceData>: Send + 'static {
    fn load(&mut self, request: DataLoadRequest<'_, Key, Data>);
}

pub trait CommitToUpstream<Key: Send, Data: ServiceData>: Send + 'static {
    fn commit(&mut self, request: DataCommitRequest<'_, Key, Data>);
}

pub trait UpstreamFactory<Key: Send, Data: ServiceData> {
    type Upstream: LoadFromUpstream<Key, Data>;

    fn create(&mut self) -> Self::Upstream;
}

impl<Key: Send, Data: ServiceData, T: Clone + LoadFromUpstream<Key, Data>>
    UpstreamFactory<Key, Data> for T
{
    type Upstream = Self;

    fn create(&mut self) -> Self::Upstream {
        self.clone()
    }
}

pub trait MutableUpstreamFactory<Key: Send, Data: ServiceData> {
    type Upstream: LoadFromUpstream<Key, Data> + CommitToUpstream<Key, Data>;

    fn create(&mut self) -> Self::Upstream;
}

impl<
        Key: Send,
        Data: ServiceData,
        T: Clone + LoadFromUpstream<Key, Data> + CommitToUpstream<Key, Data>,
    > MutableUpstreamFactory<Key, Data> for T
{
    type Upstream = Self;

    fn create(&mut self) -> Self::Upstream {
        self.clone()
    }
}

/// Marks data that can be managed through thingvellir.
pub trait ServiceData: Send + 'static {
    /// Hint to signal if data should be sent to a [CommitToUpstream].
    /// Return `false` if the data should be returned but not upstreamed.
    /// Defaults to `true`
    fn should_persist(&self) -> bool {
        true
    }

    /// Indicates when the data is considered stale and should be evicted from the cache.
    /// `None` indicates that the data should live forever.
    fn get_expires_at(&self) -> Option<&Instant> {
        None
    }
}

impl<T: ServiceData> ServiceData for Option<T> {
    fn should_persist(&self) -> bool {
        self.is_some()
    }

    fn get_expires_at(&self) -> Option<&Instant> {
        self.as_ref().and_then(|x| x.get_expires_at())
    }
}
