//! 管理员鉴权中间件（在 auth_middleware 之后）：校验用户状态与管理员角色。

use crate::{
    error::ErrorResponse, infra::middleware::UserId, repositories::user_repository::UserRepository,
    AppState,
};
use axum::{extract::Request, extract::State, middleware::Next, response::Response};

pub async fn require_admin(
    State(state): State<AppState>,
    req: Request,
    next: Next,
) -> Result<Response, ErrorResponse> {
    let user_id = req
        .extensions()
        .get::<UserId>()
        .cloned()
        .ok_or_else(|| ErrorResponse::unauthorized("not authenticated"))?;
    let user = UserRepository::new(state.pool.clone())
        .find_by_id_raw(&user_id.0)
        .await
        .map_err(|e| ErrorResponse::internal(e.to_string()))?
        .ok_or_else(|| ErrorResponse::unauthorized("user not found"))?;
    if user.status != "active" {
        return Err(ErrorResponse::forbidden("account is not active"));
    }
    if user.role != "admin" {
        return Err(ErrorResponse::forbidden("admin privilege required"));
    }
    Ok(next.run(req).await)
}
