/*
{"totpToken":"totp-mH9eLzA9Q5WB-sg3Fq8CfkP13eTh3DxF25kVK2VEDOk","code":"266242"}
{"errors":[{"code":"ERR_INVALID_TOTP_TOKEN","message":"TOTP token does not exist (maybe it expired?)","path":"totpToken"}]}


{"totpToken":"totp-gaUDaxPrrIBc8GEQ6z0vPisT8k0MEP1fgI8FA2ztLMw","code":"175543"}
{"data":{"authToken":"auth-O7mugxdYta-RKtLMqDW4j8XCJ85EfZKKezeZZXBYtFQ"},"metadata":{}}
*/

use rocket::http::{ContentType, Status};
use crate::auth::PartialUserInfo;
use rocket::post;
use rocket::serde::json::Json;
use rocket::State;
use serde::{Serialize, Deserialize};
use sqlx::PgPool;
use crate::tokens::{generate_auth_token, use_totp_token, verify_totp_token};

#[derive(Serialize, Deserialize)]
pub struct VerifyTotpAuthenticatorRequest {
    #[serde(rename = "totpToken")]
    pub totp_token: String,
    pub code: String,
}

#[derive(Serialize, Deserialize)]
pub struct VerifyTotpAuthenticatorResponseMetadata {}

#[derive(Serialize, Deserialize)]
pub struct VerifyTotpAuthenticatorResponseData {
    #[serde(rename = "authToken")]
    pub auth_token: String,
}

#[derive(Serialize, Deserialize)]
pub struct VerifyTotpAuthenticatorResponse {
    pub data: VerifyTotpAuthenticatorResponseData,
    pub metadata: VerifyTotpAuthenticatorResponseMetadata,
}

#[post("/v1/verify-totp-authenticator", data = "<req>")]
pub async fn verify_totp_authenticator_request(req: Json<VerifyTotpAuthenticatorRequest>, db: &State<PgPool>, user: PartialUserInfo) -> Result<(ContentType, Json<VerifyTotpAuthenticatorResponse>), (Status, String)> {
    let totpmachine = match verify_totp_token(req.0.totp_token.clone(), user.email.clone(), db.inner()).await {
        Ok(t) => t,
        Err(e) => return Err((Status::Unauthorized, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{} - {}\"}}]}}", "ERR_UNAUTHORIZED", "this token is invalid", e)))
    };
    if !totpmachine.check_current(&req.0.code).unwrap() {
        return Err((Status::Unauthorized, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{}\",\"path\":\"totpToken\"}}]}}", "ERR_INVALID_TOTP_TOKEN", "TOTP token does not exist (maybe it expired?)")))
    }
    match use_totp_token(req.0.totp_token, user.email, db.inner()).await {
        Ok(_) => (),
        Err(e) => return Err((Status::InternalServerError, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{} - {}\"}}]}}", "ERR_UNABLE_TO_ISSUE", "an error occured trying to issue a session token, please try again later", e)))
    }
    Ok((ContentType::JSON, Json(VerifyTotpAuthenticatorResponse {
        data: VerifyTotpAuthenticatorResponseData { auth_token: match generate_auth_token(user.user_id as i64, user.session_id, db.inner()).await {
            Ok(at) => at,
            Err(e) => return Err((Status::InternalServerError, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{} - {}\"}}]}}", "ERR_UNABLE_TO_ISSUE", "an error occured trying to issue a session token, please try again later", e)))
        } },
        metadata: VerifyTotpAuthenticatorResponseMetadata {},
    })))
}