// Module deals endpoints pertaining to admin-only actions

use hyper::{Response, Body};
use hyper::StatusCode;

use mysql_async::Pool;

use serde_json::Value;

use crate::perms::ADMIN_PERMS;

use db::{
    self,
    member::Member
};

macro_rules! get_target_id {
    ($obj:expr) => {
        match $obj.get("target-id") {
            Some(val) => val.as_u64(),
            None => None
        }
    }
}

pub async fn new_admin(p: &Pool, response: &mut Response<Body>, params: Value) {
    // @requires: owner level permission as regular admins can have conflict of interests
    // @user-param: "target-id": Number

    if let Some(uid) = get_target_id!(params) {

        if let Err(e) = Member::update_perms(p, uid, ADMIN_PERMS).await {
            eprintln!("{}", e);
        }
    }
    else {
        // this is likely the users fault providing shit ass json
        *response.status_mut() = StatusCode::BAD_REQUEST;
        *response.body_mut() = Body::from("Missing target user id");
    }
}


pub async fn set_permissions(p: &Pool, response: &mut Response<Body>, params: Value) {
    // @requiresL: admin level permissions, admins can't touch other admins
    let tuid = get_target_id!(params);

    let new_perms_opt = match params.get("permissions") {
        Some(val) => val.as_u64(),
        None => None
    };

    match (tuid, new_perms_opt) {
        (Some(uid), Some(new_perms)) => {
            // Returns Ok(Response::sucess) | Err(log)
            if let Err(e) = Member::update_perms(p, uid, new_perms).await {
                eprintln!("{}", e); // wil be some sql error
            }
        },
        _ => {
            *response.status_mut() = StatusCode::BAD_REQUEST;
            *response.body_mut() = Body::from("Missing one or more parameters");
        }
    }
}
