use log::warn;
use reqwest::Client;
use rocket::{
    get,
    http::CookieJar,
    serde::json::{json, Value as JsonValue},
    State,
};
use serde::{Deserialize, Serialize};
use serenity::model::{id::GuildId, permissions::Permissions};

use crate::web::consts::DISCORD_API;

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

#[derive(Deserialize)]
struct PartialGuild {
    pub id: GuildId,
    pub name: String,
    #[serde(default)]
    pub owner: bool,
    #[serde(rename = "permissions_new")]
    pub permissions: Option<String>,
}

#[get("/api/user/guilds")]
pub async fn get_user_guilds(cookies: &CookieJar<'_>, reqwest_client: &State<Client>) -> JsonValue {
    offline!(json!(vec![GuildInfo { id: "1".to_string(), name: "Guild".to_string() }]));

    if let Some(access_token) = cookies.get_private("access_token") {
        let request_res = reqwest_client
            .get(format!("{}/users/@me/guilds", DISCORD_API))
            .bearer_auth(access_token.value())
            .send()
            .await;

        match request_res {
            Ok(response) => {
                let guilds_res = response.json::<Vec<PartialGuild>>().await;

                match guilds_res {
                    Ok(guilds) => {
                        let reduced_guilds = guilds
                            .iter()
                            .filter(|g| {
                                g.owner
                                    || g.permissions.as_ref().map_or(false, |p| {
                                        let permissions =
                                            Permissions::from_bits_truncate(p.parse().unwrap());

                                        permissions.manage_messages()
                                            || permissions.manage_guild()
                                            || permissions.administrator()
                                    })
                            })
                            .map(|g| GuildInfo { id: g.id.to_string(), name: g.name.to_string() })
                            .collect::<Vec<GuildInfo>>();

                        json!(reduced_guilds)
                    }

                    Err(e) => {
                        warn!("Error constructing user from request: {:?}", e);

                        json!({"error": "Could not get user details"})
                    }
                }
            }

            Err(e) => {
                warn!("Error getting user guilds: {:?}", e);

                json!({"error": "Could not reach Discord"})
            }
        }
    } else {
        json!({"error": "Not authorized"})
    }
}
