use axum::{extract::FromRequestParts, http::request::Parts};
use axum_extra::TypedHeader;
use axum_extra::headers::Authorization;
use headers::authorization::Bearer;

use crate::errors::AppError;

pub struct AuthenticatedClient {
    pub token: String,
    pub client_id: String,
}

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> {
        // Extract bearer token from Authorization header
        let TypedHeader(Authorization(bearer)) = TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state)
            .await
            .map_err(|_| AppError::AuthError("Missing or invalid bearer token".to_string()))?;

        let token = bearer.token().to_string();

        // Derive client_id from the token prefix
        let client_id = format!("client_{}", &token[..8.min(token.len())]);

        Ok(AuthenticatedClient { token, client_id })
    }
}

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())
}
