// 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 chrono::{NaiveDateTime, Utc};
use serde::{Serialize, Deserialize};
use rocket::{options, get, State};
use rocket::http::{ContentType, Status};
use rocket::serde::json::Json;
use sqlx::PgPool;
use crate::auth::PartialUserInfo;
use crate::org::get_org_by_owner_id;
use crate::tokens::user_has_totp;

#[derive(Serialize, Deserialize)]
pub struct WhoamiMetadata {}

#[derive(Serialize, Deserialize)]
pub struct WhoamiActor {
    pub id: String,
    #[serde(rename = "organizationID")]
    pub organization_id: String,
    pub email: String,
    #[serde(rename = "createdAt")]
    pub created_at: String,
    #[serde(rename = "hasTOTPAuthenticator")]
    pub has_totpauthenticator: bool,
}

#[derive(Serialize, Deserialize)]
pub struct WhoamiData {
    #[serde(rename = "actorType")]
    pub actor_type: String,
    pub actor: WhoamiActor,
}

#[derive(Serialize, Deserialize)]
pub struct WhoamiResponse {
    pub data: WhoamiData,
    pub metadata: WhoamiMetadata,
}

#[options("/v2/whoami")]
pub fn options() -> &'static str {
    ""
}

#[get("/v2/whoami")]
pub async fn whoami_request(user: PartialUserInfo, db: &State<PgPool>) -> Result<(ContentType, Json<WhoamiResponse>), (Status, String)> {
    let org = match get_org_by_owner_id(user.user_id, db.inner()).await {
        Ok(b) => match b {
            Some(r) => r.to_string(),
            None => String::new()
        },
        Err(e) => return Err((Status::InternalServerError, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{} - {}\"}}]}}", "ERR_DBERROR", "an error occured trying to verify your user", e)))
    };
    Ok((ContentType::JSON, Json(WhoamiResponse {
        data: WhoamiData {
            actor_type: "user".to_string(),
            actor: WhoamiActor {
                id: user.user_id.to_string(),
                organization_id: org,
                email: user.email,
                created_at: NaiveDateTime::from_timestamp_opt(user.created_at, 0).unwrap().and_local_timezone(Utc).unwrap().to_rfc3339(),
                has_totpauthenticator: match user_has_totp(user.user_id, db.inner()).await {
                    Ok(b) => b,
                    Err(e) => return Err((Status::InternalServerError, format!("{{\"errors\":[{{\"code\":\"{}\",\"message\":\"{} - {}\"}}]}}", "ERR_DBERROR", "an error occured trying to verify your user", e)))
                },
            }
        },
        metadata: WhoamiMetadata {},
    })))
}