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

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

            if (user && user.class) {
                console.log(`🔄 Returning student detected: ${member.user.tag}`);
                if (guildConfig.visitorRole) {
                    await member.roles.remove(guildConfig.visitorRole);
                }
                if (guildConfig.studentRole) {
                    await member.roles.add(guildConfig.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 {
                if (guildConfig.visitorRole) {
                    await member.roles.add(guildConfig.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;
