use axum::extract::State;
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use super::super::auth::{ApiError, AppState, resolve_auth};
use super::super::types::{HttpExchangeKeyRequest, HttpExchangeKeyResponse};
pub async fn exchange_key(
headers: HeaderMap,
State(state): State<AppState>,
axum::Json(body): axum::Json<HttpExchangeKeyRequest>,
) -> Result<impl IntoResponse, ApiError> {
let (identity, _auth_ctx) = resolve_auth(&headers, &state, "http")?;
let auth_user_id = identity.user_id.to_string();
let rate_limit_qps = body.rate_limit_qps.unwrap_or(0);
let rate_limit_burst = body.rate_limit_burst.unwrap_or(0);
let expires_days = body.expires_days.unwrap_or(0);
let token = state.shared.auth_api_keys.create_key(
&auth_user_id,
identity.tenant_id.as_u64(),
body.scopes,
rate_limit_qps,
rate_limit_burst,
expires_days,
);
let expires_in = if expires_days > 0 {
expires_days * 86_400
} else {
0
};
state.shared.audit_record(
crate::control::security::audit::AuditEvent::AdminAction,
Some(identity.tenant_id),
&identity.username,
&format!("JWT exchanged for auth API key for user '{auth_user_id}'"),
);
Ok(axum::Json(HttpExchangeKeyResponse {
api_key: token,
auth_user_id,
expires_in,
}))
}