use axum::{
    extract::FromRequestParts,
    http::request::Parts,
    response::Redirect,
};
use tower_sessions::Session;

use irc_now_common::auth::UserClaims;

pub struct AuthUser(pub UserClaims);

impl FromRequestParts<crate::state::AppState> for AuthUser {
    type Rejection = Redirect;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &crate::state::AppState,
    ) -> Result<Self, Self::Rejection> {
        let session = Session::from_request_parts(parts, state)
            .await
            .map_err(|_| Redirect::temporary("/auth/login"))?;

        let claims: Option<UserClaims> = session
            .get("user")
            .await
            .unwrap_or(None);

        match claims {
            Some(c) => Ok(AuthUser(c)),
            None => Err(Redirect::temporary("/auth/login")),
        }
    }
}
