use rocket::http::{ContentType, Status};
use rocket::serde::json::Json;
use rocket::{State, post};
use sqlx::PgPool;
use serde::{Serialize, Deserialize};
use crate::auth::PartialUserInfo;
use crate::config::TFConfig;
use crate::tokens::{create_totp_token, user_has_totp};

#[derive(Deserialize)]
pub struct TotpAuthenticatorsRequest {}
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpAuthenticatorsResponseMetadata {}
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpAuthenticatorsResponseData {
    #[serde(rename = "totpToken")]
    pub totp_token: String,
    pub secret: String,
    pub url: String,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpAuthenticatorsResponse {
    pub data: TotpAuthenticatorsResponseData,
    pub metadata: TotpAuthenticatorsResponseMetadata,
}

#[post("/v1/totp-authenticators", data = "<_req>")]
pub async fn totp_authenticators_request(_req: Json<TotpAuthenticatorsRequest>, user: PartialUserInfo, db: &State<PgPool>, config: &State<TFConfig>) -> Result<(ContentType, Json<TotpAuthenticatorsResponse>), (Status, String)> {
    if match user_has_totp(user.user_id, db.inner()).await {
        Ok(b) => b,
        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)))
    } {
        return Err((Status::BadRequest, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{}\"}}]}}", "ERR_TOTP_ALREADY_EXISTS", "this user already has a totp authenticator on their account")))
    }

    // generate a totp token
    let (totptoken, totpmachine) = match create_totp_token(user.email, db.inner(), config.inner()).await {
        Ok(t) => t,
        Err(e) => return Err((Status::InternalServerError, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{} - {}\"}}]}}", "ERR_UNABLE_TO_ISSUE", "an error occured issuing a totp token, try again later", e)))
    };

    Ok((ContentType::JSON, Json(TotpAuthenticatorsResponse {
        data: TotpAuthenticatorsResponseData {
            totp_token: totptoken,
            secret: totpmachine.get_secret_base32(),
            url: totpmachine.get_url(),
        },
        metadata: TotpAuthenticatorsResponseMetadata {},
    })))
}