use rocket::{get, http::CookieJar, serde::json::json, State};
use serde::Serialize;
use serenity::{
    client::Context,
    model::{
        channel::GuildChannel,
        id::{ChannelId, GuildId},
    },
};

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

#[derive(Serialize)]
struct ChannelInfo {
    id: String,
    name: String,
    webhook_avatar: Option<String>,
    webhook_name: Option<String>,
}

#[get("/api/guild/<id>/channels")]
pub async fn get_guild_channels(
    id: u64,
    cookies: &CookieJar<'_>,
    ctx: &State<Context>,
) -> JsonResult {
    offline!(Ok(json!(vec![ChannelInfo {
        name: "general".to_string(),
        id: "1".to_string(),
        webhook_avatar: None,
        webhook_name: None,
    }])));
    check_authorization(cookies, ctx.inner(), id).await?;

    match GuildId::new(id).to_guild_cached(ctx.inner()) {
        Some(guild) => {
            let mut channels = guild
                .channels
                .iter()
                .filter(|(_, channel)| channel.is_text_based())
                .map(|(id, channel)| (id.to_owned(), channel.to_owned()))
                .collect::<Vec<(ChannelId, GuildChannel)>>();

            channels.sort_by(|(_, c1), (_, c2)| c1.position.cmp(&c2.position));

            let channel_info = channels
                .iter()
                .map(|(channel_id, channel)| ChannelInfo {
                    name: channel.name.to_string(),
                    id: channel_id.to_string(),
                    webhook_avatar: None,
                    webhook_name: None,
                })
                .collect::<Vec<ChannelInfo>>();

            Ok(json!(channel_info))
        }

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