// trifid-api, an open source reimplementation of the Defined Networking nebula management server.
//     Copyright (C) 2023 c0repwn3r
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU General Public License as published by
//     the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     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 General Public License for more details.
//
//     You should have received a copy of the GNU General Public License
//     along with this program.  If not, see <https://www.gnu.org/licenses/>.

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};
use rocket::options;

#[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,
}

#[options("/v1/verify-totp-authenticator")]
pub async fn options() -> &'static str {
    ""
}


#[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_CODE", "Invalid TOTP code")))
    }
    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 {},
    })))
}