// 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 crate::auth::PartialUserInfo;
use serde::{Serialize, Deserialize};
use rocket::{post, State};
use sqlx::PgPool;
use rocket::options;
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
}

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


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