import { Events } from "discord.js";
import type { Event } from "@lib/types";
import { config } from "@lib/config";
import { userService } from "@modules/user/user.service";

// Visitor role 
const event: Event<Events.GuildMemberAdd> = {
    name: Events.GuildMemberAdd,
    execute: async (member) => {
        console.log(`👤 New member joined: ${member.user.tag} (${member.id})`);
        try {
            const user = await userService.getUserById(member.id);

            if (user && user.class) {
                console.log(`🔄 Returning student detected: ${member.user.tag}`);
                await member.roles.remove(config.visitorRole);
                await member.roles.add(config.studentRole);

                if (user.class.roleId) {
                    await member.roles.add(user.class.roleId);
                    console.log(`Restored class role ${user.class.name} to ${member.user.tag}`);
                }
                console.log(`Restored student role to ${member.user.tag}`);
            } else {
                await member.roles.add(config.visitorRole);
                console.log(`Assigned visitor role to ${member.user.tag}`);
            }
            console.log(`User Roles: ${member.roles.cache.map(role => role.name).join(", ")}`);
        } catch (error) {
            console.error(`Failed to handle role assignment for ${member.user.tag}:`, error);
        }
    },
};

export default event;
