use crate::{
    domain::api::{
        models::user::ActivationToken,
        ports::ApiService,
        prelude::{Alert, FlashBag, FlashMessage},
    },
    inbound::http::state::AppState,
};

use axum::{
    extract::{Path, State},
    response::{IntoResponse, Redirect, Response},
};
use tracing::warn;

pub async fn activate_account<S: ApiService>(
    State(app_state): State<AppState<S>>,
    session: axum_session::SessionAnySession,
    Path(token): Path<String>,
) -> Response {
    let app = app_state.api_service();

    let token = ActivationToken::from(token);

    if let Err(e) = app.activate_user_account(token).await {
        warn!("{:#?}", e);
        let flash =
            FlashMessage::new("login", "Invalid activation token").with_alert(Alert::Warning);

        FlashBag::new(session).set(flash);

        return Redirect::to("/auth/login").into_response();
    }

    let flash = FlashMessage::new("login", "Activation successful, you can now login")
        .with_alert(Alert::Success);

    FlashBag::new(session).set(flash);
    Redirect::to("/auth/login").into_response()
}
