package me.proxylink.plugin;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.SecureRandom;
import java.util.HexFormat;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Logger;

final class SecretTokenBootstrap {
    private static final SecureRandom SECURE_RANDOM = new SecureRandom();
    private static final HexFormat HEX = HexFormat.of().withLowerCase();

    private SecretTokenBootstrap() {
    }

    static void prepare(Path configPath, Logger logger) throws IOException {
        Properties properties = new Properties();
        try (InputStream input = Files.newInputStream(configPath)) {
            properties.load(input);
        }

        String currentToken = properties.getProperty("tunnel.authToken", "");
        if (!needsGeneratedToken(currentToken)) {
            return;
        }

        String generatedToken = generateToken();
        ConfigFileEditor.setProperty(configPath, "tunnel.authToken", generatedToken);
        logger.warning("Generated a new DirtSimpleP2P secret token in " + configPath
                + ". Copy this same token to the other server's DirtSimpleP2P config.");
    }

    private static String generateToken() {
        byte[] bytes = new byte[32];
        SECURE_RANDOM.nextBytes(bytes);
        return HEX.formatHex(bytes);
    }

    private static boolean needsGeneratedToken(String value) {
        if (value == null || value.isBlank()) {
            return true;
        }
        String normalized = value.toLowerCase(Locale.ROOT);
        return normalized.contains("change_me")
                || normalized.contains("replace-with")
                || normalized.contains("placeholder")
                || normalized.contains("auto_generated");
    }
}
