/*
 *   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.listeners;

import de.steamwar.sql.Event;
import de.steamwar.velocitycore.VelocityCore;
import de.steamwar.velocitycore.discord.DiscordBot;
import de.steamwar.velocitycore.discord.channels.InteractionReply;
import net.dv8tion.jda.api.events.interaction.component.StringSelectInteractionEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;

public class DiscordTeamEvent extends ListenerAdapter {

    private final String eventsChannel = DiscordBot.getInstance().getConfig().channel("events");

    @Override
    public void onStringSelectInteraction(@NotNull StringSelectInteractionEvent event) {
        if (!event.getChannel().getId().equals(eventsChannel)) return;

        if (event.getSelectedOptions().isEmpty()) {
            event.deferReply(true).queue();
            return;
        }

        InteractionReply.reply(event, reply -> {
            int eventId;
            try {
                eventId = Integer.parseInt(event.getSelectedOptions().get(0).getValue());
            } catch (NumberFormatException e) {
                reply.system("UNKNOWN_EVENT");
                return;
            }

            if (reply.user().getId() == 0) {
                reply.system("DC_UNLINKED");
                return;
            }

            Event tournament = Event.byId(eventId);
            if (tournament == null) {
                reply.system("UNKNOWN_EVENT");
                return;
            }

            VelocityCore.get().getTeamCommand().event(reply, tournament);
        });
    }
}
