// Module deals endpoints pertaining to admin-only actions

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

use mysql_async::Pool;

use std::collections::HashMap;

use crate::perms::ADMIN_PERMS;

use db::{self, Member};

use crate::qs_param;


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

    let uid = qs_param!(params, "target-id", u64);
    if let Some(uid) = uid {
        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: HashMap<String, String>) {
    // @requiresL: admin level permissions, admins can't touch other admins
    let target_uid = qs_param!(params, "id", u64);

    let new_perms_opt = qs_param!(params, "permissions", u64);

    match (target_uid, 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");
        }
    }
}
