mod channels;
mod emojis;
mod reminders;
mod roles;
mod templates;
pub mod todos;

use std::env;

pub use channels::get_guild_channels;
pub use emojis::get_guild_emojis;
pub use reminders::*;
use rocket::{get, http::CookieJar, serde::json::json, State};
pub use roles::get_guild_roles;
use serenity::{
    client::Context,
    model::id::{GuildId, RoleId},
};
pub use templates::*;

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

#[get("/api/guild/<id>")]
pub async fn get_guild_info(id: u64, cookies: &CookieJar<'_>, ctx: &State<Context>) -> JsonResult {
    offline!(Ok(json!({ "patreon": true, "name": "Guild" })));
    check_authorization(cookies, ctx.inner(), id).await?;

    match GuildId::new(id)
        .to_guild_cached(ctx.inner())
        .map(|guild| (guild.owner_id, guild.name.clone()))
    {
        Some((owner_id, name)) => {
            let member_res = GuildId::new(env::var("PATREON_GUILD_ID").unwrap().parse().unwrap())
                .member(&ctx.inner(), owner_id)
                .await;

            let patreon = member_res.map_or(false, |member| {
                member
                    .roles
                    .contains(&RoleId::new(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap()))
            });

            Ok(json!({ "patreon": patreon, "name": name }))
        }

        None => json_err!("Bot not in guild"),
    }
}
