use super::LOG_TARGET;
use axum::extract::Request;
use axum::middleware::Next;
use axum::response::Response;
use axum_extra::extract::cookie::CookieJar;
use scopeguard::defer;
use std::sync::Arc;
use tibba_state::{CTX, Context};
use tibba_util::{
get_device_id_from_cookie, set_header_if_not_exist, set_no_cache_if_not_exist, uuid,
};
use tracing::debug;
pub async fn entry(jar: CookieJar, mut req: Request, next: Next) -> Response {
debug!(target: LOG_TARGET, "--> entry");
defer!(debug!(target: LOG_TARGET, "<-- entry"););
let device_id = get_device_id_from_cookie(&jar).unwrap_or_default();
let ctx = Arc::new(Context::new(device_id, uuid()));
req.extensions_mut().insert(ctx.clone());
let mut res = CTX.scope(ctx.clone(), async { next.run(req).await }).await;
let headers = res.headers_mut();
set_no_cache_if_not_exist(headers);
let _ = set_header_if_not_exist(headers, "X-Trace-Id", &ctx.trace_id);
res
}