use axum::{extract::FromRequestParts, http::request::Parts};

use crate::errors::AppError;

#[derive(Debug, Clone)]
pub struct AuthInfo {
    pub token: String,
    pub client_id: String,
}

pub struct AuthenticatedClient {
    pub info: AuthInfo,
}

impl<S> FromRequestParts<S> for AuthenticatedClient
where
    S: Send + Sync,
{
    type Rejection = AppError;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        // Retrieve AuthInfo from request extensions, where it was placed by rate_limit_middleware
        let info = parts
            .extensions
            .get::<AuthInfo>()
            .cloned()
            .ok_or_else(|| AppError::AuthError("Authentication info not found in request".to_string()))?;

        Ok(AuthenticatedClient { info })
    }
}

impl std::ops::Deref for AuthenticatedClient {
    type Target = AuthInfo;

    fn deref(&self) -> &Self::Target {
        &self.info
    }
}

pub fn validate_token(token: &str, valid_tokens: &[String]) -> bool {
    // Simple validation against list of tokens
    // In production, use proper token validation (JWT, database lookup, etc.)
    valid_tokens.contains(&token.to_string())
}
