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

pub const TOTP_GENERIC_UNAUTHORIZED_ERROR: &str = "{\"errors\":[{\"code\":\"ERR_INVALID_TOTP_CODE\",\"message\":\"invalid TOTP code (maybe it expired?)\",\"path\":\"code\"}]}";
pub const TOTP_NO_TOTP_ERROR: &str = "{\"errors\":[{\"code\":\"ERR_NO_TOTP\",\"message\":\"logged-in user does not have totp enabled\",\"path\":\"code\"}]}";

#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpRequest {
    pub code: String
}

#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpResponseData {
    #[serde(rename = "authToken")]
    auth_token: String
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpResponseMetadata {
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
pub struct TotpResponse {
    data: TotpResponseData,
    metadata: TotpResponseMetadata
}

#[post("/v1/auth/totp", data = "<req>")]
pub async fn totp_request(req: Json<TotpRequest>, user: PartialUserInfo, db: &State<PgPool>) -> Result<(ContentType, Json<TotpResponse>), (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::UnprocessableEntity, TOTP_NO_TOTP_ERROR.to_string()))
    }

    if user.has_totp_auth {
        return Err((Status::BadRequest, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{}\"}}]}}", "ERR_TOTP_ALREADY_AUTHED", "user already has valid totp authentication")))
    }

    let totpmachine = match get_totpmachine(user.user_id, db.inner()).await {
        Ok(t) => t,
        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)))
        }
    };

    if !totpmachine.check_current(&req.0.code).unwrap_or(false) {
        return Err((Status::Unauthorized, TOTP_GENERIC_UNAUTHORIZED_ERROR.to_string()))
    }

    Ok((ContentType::JSON, Json(TotpResponse {
        data: TotpResponseData { auth_token: match generate_auth_token(user.user_id as i64, user.session_id, db.inner()).await {
            Ok(t) => t,
            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: TotpResponseMetadata {},
    })))
}