// src/auth/middleware.rs
use tonic::{service::Interceptor, Status};
use crate::auth::logic::jwt;

pub struct AuthInterceptor;

impl Interceptor for AuthInterceptor {
    fn call(&mut self, mut request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
        let metadata = request.metadata();
        let token = metadata.get("authorization")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.strip_prefix("Bearer "))
            .ok_or(Status::unauthenticated("Missing authorization header"))?;

        let claims = jwt::validate_token(token)
            .map_err(|e| Status::unauthenticated(e.to_string()))?;

        // Store claims in request extensions
        request.extensions_mut().insert(claims);
        Ok(request)
    }
}
