use axum::{
    extract::{Request, State},
    http::StatusCode,
    middleware::Next,
    response::{IntoResponse, Response},
};
use std::sync::Arc;
use wheel_rs::urn_utils::Urn;

#[derive(Clone)]
pub struct ForbiddenUrnsState {
    pub(crate) forbidden_urns: Arc<Vec<Urn>>,
}

pub async fn forbidden_urns_middleware(
    State(state): State<ForbiddenUrnsState>,
    request: Request,
    next: Next,
) -> Response {
    let request_method = request.method().to_string().to_uppercase();
    let request_uri = request.uri().path();

    if state
        .forbidden_urns
        .iter()
        .any(|forbidden_urn| forbidden_urn.matches(&request_method, request_uri))
    {
        return StatusCode::FORBIDDEN.into_response();
    }

    next.run(request).await
}
