//! Minimal authentication interceptor for Trading Service
//!
//! NOTE: Authentication is handled by API Gateway (Wave 70)
//! This module provides minimal types for compatibility with existing code.
//! All actual authentication, authorization, and JWT validation occurs in API Gateway.

use serde::{Deserialize, Serialize};
use std::time::Instant;
use tonic::Status;

/// User role for RBAC
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UserRole {
    Admin,
    Trader,
    Analyst,
    RiskManager,
    ComplianceOfficer,
    ReadOnly,
}

impl UserRole {
    /// Get permissions for this role
    pub fn get_permissions(&self) -> Vec<&'static str> {
        match self {
            UserRole::Admin => vec!["*"],
            UserRole::Trader => vec!["trading.submit_order", "trading.cancel_order"],
            UserRole::Analyst => vec!["analytics.run_backtest"],
            UserRole::RiskManager => vec!["risk.modify_limits"],
            UserRole::ComplianceOfficer => vec!["compliance.view_reports"],
            UserRole::ReadOnly => vec!["*.view"],
        }
    }
}

/// JWT claims structure
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JwtClaims {
    pub jti: String,
    pub sub: String,
    pub iat: u64,
    pub exp: u64,
    pub iss: String,
    pub aud: String,
    pub roles: Vec<String>,
    pub permissions: Vec<String>,
    #[serde(default = "default_token_type")]
    pub token_type: String,
    #[serde(default)]
    pub session_id: Option<String>,
}

fn default_token_type() -> String {
    "access".to_string()
}

/// Authentication methods (minimal stub - API Gateway handles actual auth)
#[derive(Debug, Clone, PartialEq)]
pub enum AuthMethod {
    JwtToken(JwtClaims),
    ApiKey(ApiKeyInfo),
}

/// API key information
#[derive(Debug, Clone, PartialEq)]
pub struct ApiKeyInfo {
    pub key_id: String,
    pub user_id: String,
    pub permissions: Vec<String>,
    pub expires_at: u64,
}

/// Authentication context (minimal stub - API Gateway handles actual auth)
#[derive(Debug, Clone)]
pub struct AuthContext {
    pub user_id: String,
    pub auth_method: AuthMethod,
    pub role: UserRole,
    pub permissions: Vec<String>,
    pub request_time: Instant,
    pub client_ip: Option<String>,
}

impl AuthContext {
    pub fn has_permission(&self, permission: &str) -> bool {
        self.permissions.contains(&permission.to_string())
    }

    pub fn has_any_permission(&self, permissions: &[&str]) -> bool {
        permissions
            .iter()
            .any(|p| self.permissions.contains(&p.to_string()))
    }

    pub fn has_all_permissions(&self, permissions: &[&str]) -> bool {
        permissions
            .iter()
            .all(|p| self.permissions.contains(&p.to_string()))
    }

    pub fn get_auth_age_ms(&self) -> u64 {
        self.request_time.elapsed().as_millis() as u64
    }
}

/// Authentication configuration (minimal stub - API Gateway handles actual auth)
#[derive(Debug, Clone)]
pub struct AuthConfig {
    pub enable_jwt: bool,
    pub enable_api_keys: bool,
    pub enable_mtls: bool,
    pub jwt_issuer: String,
    pub jwt_audience: String,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            enable_jwt: false,      // API Gateway handles JWT
            enable_api_keys: false, // API Gateway handles API keys
            enable_mtls: false,     // API Gateway handles mTLS
            jwt_issuer: "foxhunt-api".to_string(),
            jwt_audience: "foxhunt-trading-service".to_string(),
        }
    }
}

/// Minimal Tonic interceptor (no-op - API Gateway handles actual auth)
#[derive(Debug, Clone)]
pub struct TonicAuthInterceptor {
    _config: AuthConfig,
}

impl TonicAuthInterceptor {
    pub fn new(config: AuthConfig) -> Self {
        Self { _config: config }
    }
}

impl tonic::service::Interceptor for TonicAuthInterceptor {
    fn call(&mut self, request: tonic::Request<()>) -> Result<tonic::Request<()>, Status> {
        // No-op: API Gateway performs all authentication
        // This service trusts requests forwarded by API Gateway
        Ok(request)
    }
}
