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

import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent;
import com.velocitypowered.api.event.connection.PreLoginEvent;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.proxy.connection.MinecraftConnection;
import com.velocitypowered.proxy.connection.client.ConnectedPlayer;
import com.velocitypowered.proxy.connection.client.LoginInboundConnection;
import de.steamwar.linkage.Linked;
import de.steamwar.persistent.Reflection;
import de.steamwar.velocitycore.VelocityCore;
import de.steamwar.velocitycore.mods.Hostname;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;

@Linked
public class IPSanitizer extends BasicListener {

    private static final Map<UUID, InetAddress> trueAddress = new HashMap<>(); // Will likely slightly leak over time

    public static InetAddress getTrueAddress(Player player) {
        return trueAddress.getOrDefault(player.getUniqueId(), ((InetSocketAddress) ((ConnectedPlayer) player).getConnection().getChannel().remoteAddress()).getAddress());
    }

    private static final Reflection.Field<MinecraftConnection, SocketAddress> remoteAddress = new Reflection.Field<>(MinecraftConnection.class, "remoteAddress");
    private static final InetSocketAddress sanitized = new InetSocketAddress("127.127.127.127", 25565);

    @Subscribe
    public void loginEvent(PreLoginEvent e) {
        InetSocketAddress address = e.getConnection().getRemoteAddress();
        VelocityCore.getLogger().log(Level.INFO, "%s has logged in with user name %s".formatted(address, e.getUsername()));
        trueAddress.put(e.getUniqueId(), address.getAddress());
        remoteAddress.set(Hostname.getInitialInboundConnection((LoginInboundConnection) e.getConnection()).getConnection(), sanitized);
    }

    @Subscribe
    public void disconnectEvent(DisconnectEvent e) {
        trueAddress.remove(e.getPlayer().getUniqueId());
    }
}
