/*
 *   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.velocitycore.VelocityCore;
import de.steamwar.velocitycore.discord.channels.DiscordChannel;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

@UtilityClass
public class AuthManager {

    private final Map<String, User> TOKENS = new HashMap<>();
    private final Random rand = new Random();

    public String createDiscordAuthToken(User user) {
        TOKENS.values().removeIf(user::equals);

        byte[] randBytes = new byte[16];
        rand.nextBytes(randBytes);
        String code = Base64.getEncoder().encodeToString(randBytes);

        TOKENS.put(code, user);
        VelocityCore.getLogger().log(Level.INFO, "Created Discord Auth-Token: %s for: %s".formatted(code, user.getAsTag()));
        VelocityCore.schedule(() -> TOKENS.remove(code)).delay(10, TimeUnit.MINUTES).schedule();
        return code;
    }

    public User connectAuth(SteamwarUser user, String code) {
        User dcUser = TOKENS.remove(code);
        if (dcUser == null) return null;

        user.setDiscordId(dcUser.getIdLong());

        DiscordChannel channel = new DiscordChannel(dcUser);
        channel.send(new MessageCreateBuilder()
                .setContent(channel.parseToPlain("DC_AUTH_SUCCESS", user, user.getUserName()))
                .setComponents(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")))));

        return dcUser;
    }
}
