use crate::tso::TsoOracle;
use flaredb_proto::pdpb::tso_server::Tso;
use flaredb_proto::pdpb::{TsoRequest, TsoResponse};
use std::sync::Arc;
use tonic::{Request, Response, Status};

pub struct TsoServiceImpl {
    oracle: Arc<TsoOracle>,
}

impl TsoServiceImpl {
    pub fn new(oracle: Arc<TsoOracle>) -> Self {
        Self { oracle }
    }
}

#[tonic::async_trait]
impl Tso for TsoServiceImpl {
    async fn get_timestamp(
        &self,
        request: Request<TsoRequest>,
    ) -> Result<Response<TsoResponse>, Status> {
        let req = request.into_inner();
        let count = req.count;
        let ts = self.oracle.get_timestamp(count);
        Ok(Response::new(TsoResponse {
            timestamp: ts,
            count,
        }))
    }
}
