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

use crate::utils::check_subscription;
use crate::web::guards::transaction::Transaction;
use crate::web::{check_authorization, routes::JsonResult};
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::all::UserId;
use serenity::{client::Context, model::id::GuildId};
pub use templates::*;

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

    let user_id =
        cookies.get_private("userid").map(|c| c.value().parse::<u64>().ok()).flatten().unwrap();

    match GuildId::new(id).to_guild_cached(ctx.inner()).map(|guild| guild.name.clone()) {
        Some(name) => {
            let patreon = check_subscription(
                ctx.inner(),
                transaction.executor(),
                UserId::from(user_id),
                Some(GuildId::from(id)),
            )
            .await;

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

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