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

import com.mojang.authlib.GameProfile;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.ProfileLookupCallback;
import de.steamwar.sql.SteamwarUser;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.Services;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class SteamwarGameProfileRepository implements GameProfileRepository {
    public static final SteamwarGameProfileRepository impl = new SteamwarGameProfileRepository();

    private static final GameProfileRepository fallback;
    private static final Services current;

    static {
        current = MinecraftServer.getServer().services;
        fallback = current.profileRepository();
    }

    @Override
    public void findProfilesByNames(String[] strings, ProfileLookupCallback profileLookupCallback) {
        List<String> unknownNames = new ArrayList<>();
        for (String name : strings) {
            SteamwarUser user = SteamwarUser.get(name);
            if (user == null) {
                unknownNames.add(name);
                continue;
            }

            profileLookupCallback.onProfileLookupSucceeded(new GameProfile(user.getUUID(), user.getUserName()));
        }
        if (!unknownNames.isEmpty()) {
            fallback.findProfilesByNames(unknownNames.toArray(new String[0]), profileLookupCallback);
        }
    }

    @Override
    public Optional<GameProfile> findProfileByName(String s) {
        return fallback.findProfileByName(s);
    }

    public void inject() {
        MinecraftServer.getServer().services = new Services(current.sessionService(), current.servicesKeySet(), this, current.profileCache(), current.paperConfigurations());
    }
}
