use poise::serenity_prelude as sere;
use tracing::{error, debug, trace};

pub async fn user_join(ctx: &sere::Context, new_member: &sere::Member, pool: &sqlx::PgPool) {
    trace!("User joined event handler called for guild {}", new_member.guild_id);
    // Assign role to new user if the feature is enabled
    let guild_id = new_member.guild_id.get() as u64;

    let role_result = sqlx::query!(
        "SELECT role_id FROM auto_roles WHERE guild_id = $1 AND enabled = true",
        guild_id as i64
    )
    .fetch_optional(pool)
    .await;

    trace!("Checking if auto role is enabled for guild {}", guild_id);

    match role_result {
        Ok(Some(row)) => {
            trace!("Auto role enabled for guild {}", guild_id);
            let role_id = row.role_id as u64;
            trace!("Adding role {} to user {}", role_id, new_member.user.name);
            give_role_to_user(ctx, new_member, role_id).await;
            
        }
        Ok(None) => {
            trace!("No auto role enabled for guild {}", guild_id);
        }
        Err(e) => {
            error!("Database error fetching auto role for guild {}: {:?}", guild_id, e);
        }
    }
}

async fn give_role_to_user(ctx: &sere::Context, member: &sere::Member, role_id: u64) {
    if let Err(e) = member.add_role(&ctx.http, sere::RoleId::new(role_id)).await {
        error!("Error adding role to member: {:?}", e);
        return;
    }
    debug!("Role {} added to user {} in guild {}", role_id, member.user.name, member.guild_id);
}