use crate::{Context, Error};
use poise::serenity_prelude as sere;
use tracing::trace;

pub async fn get_all_admin_users(ctx: Context<'_>) -> Result<Vec<sere::User>, Error> {
    let guild_id = ctx.guild_id().unwrap();
    let pool = &ctx.data().pool;
    let db_guild_id = guild_id.get() as i64;

    let admin_users_records = sqlx::query!("SELECT user_id FROM admin_users WHERE guild_id = $1;", db_guild_id)
        .fetch_all(pool)
        .await?;

    let admin_roles_records = sqlx::query!("SELECT role_id FROM admin_roles WHERE guild_id = $1;", db_guild_id)
        .fetch_all(pool)
        .await?;

    let admin_role_ids: std::collections::HashSet<_> = admin_roles_records
        .into_iter()
        .map(|record| sere::RoleId::new(record.role_id as u64))
        .collect();

    let mut admin_users = Vec::new();
    let mut admin_user_ids = std::collections::HashSet::new();

    for record in admin_users_records {
        let user_id = sere::UserId::new(record.user_id as u64);
        if admin_user_ids.insert(user_id) {
            if let Ok(user) = user_id.to_user(ctx.http()).await {
                admin_users.push(user);
            }
        }
    }

    let mut last_member_id = None;
    loop {
        let members = guild_id.members(ctx.http(), Some(1000), last_member_id).await?;
        if members.is_empty() {
            break;
        }
        last_member_id = Some(members.last().unwrap().user.id);

        for member in members {
            let has_role = member.roles.iter().any(|role_id| admin_role_ids.contains(role_id));
            let has_admin_perms = ctx.guild()
                .map(|g| g.member_permissions(&member).administrator())
                .unwrap_or(false);
            
            if (has_role || has_admin_perms) && admin_user_ids.insert(member.user.id) {
                admin_users.push(member.user);
            }
        }
    }

    Ok(admin_users)
}

pub async fn trace_message(msg: String, channel: String, guild: String) {
    trace!("Saying \"{}\" in channel {} in guild {}", msg, channel, guild);
}