use log::warn;
use rocket::{get, http::CookieJar, serde::json::json, State};
use serde::Serialize;
use serenity::client::Context;

use crate::web::{check_authorization, routes::JsonResult};

#[derive(Serialize)]
struct RoleInfo {
    id: String,
    name: String,
}

#[get("/api/guild/<id>/roles")]
pub async fn get_guild_roles(id: u64, cookies: &CookieJar<'_>, ctx: &State<Context>) -> JsonResult {
    offline!(Ok(json!(vec![RoleInfo { name: "@everyone".to_string(), id: "1".to_string() }])));
    check_authorization(cookies, ctx.inner(), id).await?;

    let roles_res = ctx.cache.guild(id).map(|g| {
        g.roles
            .iter()
            .map(|(_, r)| RoleInfo { id: r.id.to_string(), name: r.name.to_string() })
            .collect::<Vec<RoleInfo>>()
    });

    match roles_res {
        Some(roles) => Ok(json!(roles)),
        None => {
            warn!("Could not fetch roles from {}", id);

            json_err!("Could not get roles")
        }
    }
}
