use crate::auth_token::AuthToken;
use std::sync::Arc;
use tonic::metadata::MetadataValue;
use tonic::service::Interceptor;
use tonic::{Request, Status};

#[derive(Clone)]
pub struct AuthInterceptor {
    pub token: Arc<AuthToken>,
}

impl Interceptor for AuthInterceptor {
    fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, Status> {
        let token = self.token.get();

        let value = MetadataValue::try_from(format!("Bearer {}", token))
            .map_err(|_| Status::internal("bad auth token"))?;

        req.metadata_mut().insert("authorization", value);
        Ok(req)
    }
}
