using Noctalk.Shared.Chat.Configuration;

namespace Noctalk_server.Server.Storage;

public static class Server_startup
{
    public static void Noctalk_server__startup__ensure_runtime_folders(string The_executable_directory)
    {
        string[] relativeDirectories =
        [
            Path.Combine("Config"),
            Path.Combine("Data", "Conversations"),
            Path.Combine("Data", "Metadata"),
            Path.Combine("darknet", "tor"),
            Path.Combine("darknet", "data")
        ];

        foreach (string relativeDirectory in relativeDirectories)
        {
            Directory.CreateDirectory(Path.Combine(The_executable_directory, relativeDirectory));
        }
    }

    public static Server_config Noctalk_server__startup__ensure_main_config(string The_executable_directory)
    {
        const string relativeConfigPath = "Config/main.cfg";
        Server_config serverConfig = Base64_json_file.Read__from__relative_path<Server_config>(The_executable_directory, relativeConfigPath);

        bool configChanged = false;

        if (serverConfig.Admin__guid == Guid.Empty)
        {
            serverConfig.Admin__guid = Guid.NewGuid();
            configChanged = true;
        }

        if (string.IsNullOrWhiteSpace(serverConfig.Server__name))
        {
            serverConfig.Server__name = "My private chat server";
            configChanged = true;
        }

        if (serverConfig.Server__local_relay_port is < 1 or > 65535)
        {
            serverConfig.Server__local_relay_port = 65190;
            configChanged = true;
        }

        if (configChanged)
        {
            Base64_json_file.Write__to__relative_path(The_executable_directory, relativeConfigPath, serverConfig);
        }

        return serverConfig;
    }

    public static void Noctalk_server__startup__write_main_config(string The_executable_directory, Server_config The_server_config)
    {
        Base64_json_file.Write__to__relative_path(The_executable_directory, "Config/main.cfg", The_server_config);
    }

    public static void Noctalk_server__startup__ensure_metadata_files(string The_executable_directory, Server_config The_server_config)
    {
        string metadataDirectory = Path.Combine(The_executable_directory, "Data", "Metadata");
        string adminMetadataPath = Path.Combine(metadataDirectory, "Admin__guid.txt");

        if (!File.Exists(adminMetadataPath))
        {
            File.WriteAllText(adminMetadataPath, The_server_config.Admin__guid.ToString());
        }
    }
}
