//! Provides an Axum extractor to fetch the authenticated user for a request.

use anyhow::Result;
use async_session::{Session, SessionStore as _};
use axum::{
    RequestPartsExt,
    extract::{FromRequestParts, OriginalUri},
    http::{Method, request::Parts},
    response::{IntoResponse, Redirect, Response},
};
use axum_extra::extract::{
    CookieJar,
    cookie::{Cookie, SameSite},
};
use phono_models::user::User;
use tracing::{Instrument as _, info_span};

use crate::{
    app::{App, AppDbConn},
    auth::{AuthInfo, SESSION_KEY_AUTH_INFO, SESSION_KEY_AUTH_REDIRECT},
    errors::AppError,
    sessions::AppSession,
};

/// Extractor for the authenticated user associated with an HTTP request. If
/// the request is not authenticated, the extractor will abort request handling
/// and redirect the client to an OAuth2 login page.
#[derive(Clone, Debug)]
pub(crate) struct CurrentUser(pub(crate) User);

impl FromRequestParts<App> for CurrentUser {
    type Rejection = CurrentUserRejection;

    async fn from_request_parts(parts: &mut Parts, state: &App) -> Result<Self, Self::Rejection> {
        async {
            let mut session =
                if let AppSession(Some(value)) = parts.extract_with_state(state).await? {
                    value
                } else {
                    Session::new()
                };
            let auth_info = if let Some(value) = session.get::<AuthInfo>(SESSION_KEY_AUTH_INFO) {
                value
            } else {
                let jar: CookieJar = parts.extract().await?;
                let method: Method = parts.extract().await?;
                let jar = if method == Method::GET {
                    let OriginalUri(uri) = parts.extract().await?;
                    session.insert(
                        SESSION_KEY_AUTH_REDIRECT,
                        uri.path_and_query()
                            .map(|value| value.to_string())
                            .unwrap_or(format!("{0}/", state.settings.root_path)),
                    )?;
                    if let Some(cookie_value) = state.session_store.store_session(session).await? {
                        tracing::debug!("adding session cookie to jar");
                        jar.add(
                            Cookie::build((state.settings.auth.cookie_name.clone(), cookie_value))
                                .same_site(SameSite::Lax)
                                .http_only(true)
                                .path("/"),
                        )
                    } else {
                        tracing::debug!("inferred that session cookie already in jar");
                        jar
                    }
                } else {
                    // If request method is not GET then do not attempt to infer the
                    // redirect target, as there may be no GET handler defined for
                    // it.
                    jar
                };
                return Err(Self::Rejection::SetCookiesAndRedirect(
                    jar,
                    format!("{0}/auth/login", state.settings.root_path),
                ));
            };
            let AppDbConn(mut app_db): AppDbConn = parts.extract_with_state(state).await?;
            Ok(CurrentUser(
                if let Some(user) = User::with_uid(&auth_info.sub)
                    .fetch_optional(&mut app_db)
                    .await?
                {
                    user
                } else {
                    tracing::debug!("user record not found by uid; upserting");
                    User::upsert()
                        .uid(&auth_info.sub)
                        .email(&auth_info.email)
                        .execute(&mut app_db)
                        .await?
                },
            ))
        }
        .instrument(info_span!("CurrentUser extractor"))
        .await
    }
}

pub enum CurrentUserRejection {
    AppError(AppError),
    SetCookiesAndRedirect(CookieJar, String),
}

// Easily convert semi-arbitrary errors to InternalServerError
impl<E> From<E> for CurrentUserRejection
where
    E: Into<AppError>,
{
    fn from(err: E) -> Self {
        Self::AppError(err.into())
    }
}

impl IntoResponse for CurrentUserRejection {
    fn into_response(self) -> Response {
        match self {
            Self::AppError(err) => err.into_response(),
            Self::SetCookiesAndRedirect(jar, redirect_to) => {
                (jar, Redirect::to(&redirect_to)).into_response()
            }
        }
    }
}
