/*
 * asklyphe-auth-frontend verify.rs
 * - email verification page routes
 *
 * Copyright (C) 2025 Real Microsoft, LLC
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use std::sync::Arc;
use askama::Template;
use askama_axum::IntoResponse;
use asklyphe_common::nats::authservice::{AuthServiceQuery, AuthServiceRequest, AuthServiceResponse, VerifyEmailRequest, VerifyEmailResponse};
use asklyphe_common::nats::comms;
use asklyphe_common::nats::comms::ServiceResponse;
use async_nats::jetstream;
use axum::Extension;
use axum::extract::Query;
use serde::Deserialize;
use tokio::sync::Mutex;
use tracing::error;
use crate::{BUILT_ON, GIT_COMMIT, VERSION, YEAR};

#[derive(Template)]
#[template(path = "verify.html")]
struct VerifyTemplate {
    system_message: String,
    version: String,
    git_commit: String,
    built_on: String,
    year: String,
}

#[derive(Deserialize, Debug)]
pub struct VerifyParams {
    username: Option<String>,
    token: Option<String>,
}

pub async fn verify_get(
    Extension(nats): Extension<Arc<Mutex<jetstream::Context>>>,
    Query(params): Query<VerifyParams>,
) -> impl IntoResponse {
    fn verify_error(error: &str) -> impl IntoResponse {
        VerifyTemplate {
            system_message: format!("error: {error}"),
            version: VERSION.to_string(),
            git_commit: GIT_COMMIT.to_string(),
            built_on: BUILT_ON.to_string(),
            year: YEAR.to_string(),
        }
    }

    let username = params.username;
    let token = params.token;
    if username.is_none() || token.is_none() {
        return verify_error("one or more fields blank!").into_response();
    }
    let username = username.unwrap();
    let token = token.unwrap();
    if username.is_empty() || token.is_empty() {
        return verify_error("one or more fields blank!").into_response();
    }

    let response = comms::query_service(
        comms::Query::AuthService(AuthServiceQuery {
            request: AuthServiceRequest::VerifyEmailRequest(VerifyEmailRequest {
                username,
                token,
            }),
            replyto: "".to_string(),
        }),
        &*nats.lock().await,
        false,
    ).await;

    if let Err(e) = response {
        error!("internal server error while trying to communicate with auth service! {:?}", e);
        return verify_error("internal server error! try again, or contact an administrator if the issue persists!").into_response();
    }
    let response = response.unwrap();
    let mut internal_server_error = false;

    match &response {
        ServiceResponse::SearchService(_) => {
            error!("sent search service response when asking for auth service!! investigate ASAP!!!");
            internal_server_error = true;
        }
        ServiceResponse::BingService(_) => {
            error!("sent bing service response when asking for auth service!! investigate ASAP!!!");
            internal_server_error = true;
        }
        ServiceResponse::AuthService(r) => {
            match r {
                AuthServiceResponse::VerifyEmailResponse(_) => {}
                x => {
                    error!("auth service gave {} to our verify email query!", x);
                    internal_server_error = true;
                }
            }
        }
    }

    if internal_server_error {
        return verify_error("internal server error! try again, or contact an administrator if the issue persists!").into_response();
    }

    match response {
        ServiceResponse::AuthService(AuthServiceResponse::VerifyEmailResponse(response)) => match response {
                VerifyEmailResponse::Success => {
                    VerifyTemplate {
                        system_message: "email verified! you should be good to log in to your account now! (:".to_string(),
                        version: VERSION.to_string(),
                        git_commit: GIT_COMMIT.to_string(),
                        built_on: BUILT_ON.to_string(),
                        year: YEAR.to_string(),
                    }.into_response()
                }
                VerifyEmailResponse::InvalidToken => {
                    verify_error("invalid token").into_response()
                }
                VerifyEmailResponse::ExpiredToken => {
                    verify_error("token expired, please try signing up again, or resending the request if you're changing emails").into_response()
                }
                VerifyEmailResponse::InternalServerError(e) => {
                    error!("experienced internal server error \"{e}\" while attempting to verify email");
                    verify_error("internal server error! try again, or contact an administrator if the issue persists!").into_response()
                }
        }
        _ => unreachable!()
    }

}
