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

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

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


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