/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.velocitycore.discord.util;

import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import de.steamwar.velocitycore.discord.DiscordBot;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@UtilityClass
public class DiscordRanks {

    private final Map<UserPerm.Prefix, String> prefixToPermName = UserPerm.prefixes.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, entry -> entry.getKey().name().toLowerCase()));

    public void update(SteamwarUser user) {
        if (user.getDiscordId() == null) return;

        Set<String> swRoles = new HashSet<>(DiscordBot.getInstance().getConfig().getRanks().values());

        Guild guild = DiscordBot.getGuild();
        guild.retrieveMemberById(user.getDiscordId()).queue(member -> {
            String prefixRole = DiscordBot.getInstance().getConfig().getRanks().get(prefixToPermName.get(user.prefix()));
            member.getRoles().stream()
                    .filter(role -> swRoles.contains(role.getId()))
                    .filter(role -> !role.getId().equals(prefixRole))
                    .forEach(role -> guild.removeRoleFromMember(member, role).queue());

            if (prefixRole != null && member.getRoles().stream().noneMatch(role -> role.getId().equals(prefixRole))) {
                guild.addRoleToMember(member, guild.getRoleById(prefixRole)).queue();
            }
        }, e -> {
            if (e instanceof ErrorResponseException err && err.getErrorCode() == 10007) {
                user.setDiscordId(null);
            }
        });
    }
}
