//! Adapter from SessionStore to AgentSessionStore.

use async_trait::async_trait;
use meerkat_core::{
    AgentError, AgentSessionStore, Session, SessionId,
    error::{invalid_session_id, store_error},
};
use std::sync::Arc;

use crate::SessionStore;

/// Adapter that wraps a SessionStore to implement AgentSessionStore.
pub struct StoreAdapter<S: SessionStore + ?Sized> {
    store: Arc<S>,
}

impl<S: SessionStore + ?Sized> StoreAdapter<S> {
    pub fn new(store: Arc<S>) -> Self {
        Self { store }
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<S: SessionStore + ?Sized + 'static> AgentSessionStore for StoreAdapter<S> {
    async fn save(&self, session: &Session) -> Result<(), AgentError> {
        self.store.save(session).await.map_err(store_error)
    }

    async fn load(&self, id: &str) -> Result<Option<Session>, AgentError> {
        let session_id = SessionId::parse(id).map_err(invalid_session_id)?;

        self.store.load(&session_id).await.map_err(store_error)
    }
}
