using System.Text.Json;

namespace ScadaLink.CLI;

public class CliConfig
{
    public string? ManagementUrl { get; set; }
    public string DefaultFormat { get; set; } = "json";

    /// <summary>
    /// LDAP username from the <c>SCADALINK_USERNAME</c> environment variable, if set.
    /// Credentials are intentionally only sourced from environment variables (or the
    /// command line) — never from the config file — so they are not persisted to disk.
    /// </summary>
    public string? Username { get; set; }

    /// <summary>
    /// LDAP password from the <c>SCADALINK_PASSWORD</c> environment variable, if set.
    /// Provides a safer alternative to <c>--password</c>, which leaks into process
    /// listings and shell history.
    /// </summary>
    public string? Password { get; set; }

    public static CliConfig Load()
    {
        var config = new CliConfig();

        // Load from config file
        var configPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
            ".scadalink", "config.json");
        if (File.Exists(configPath))
        {
            var json = File.ReadAllText(configPath);
            var fileConfig = JsonSerializer.Deserialize<CliConfigFile>(json,
                new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
            if (fileConfig != null)
            {
                if (!string.IsNullOrEmpty(fileConfig.ManagementUrl))
                    config.ManagementUrl = fileConfig.ManagementUrl;
                if (!string.IsNullOrEmpty(fileConfig.DefaultFormat))
                    config.DefaultFormat = fileConfig.DefaultFormat;
            }
        }

        // Override from environment variables
        var envUrl = Environment.GetEnvironmentVariable("SCADALINK_MANAGEMENT_URL");
        if (!string.IsNullOrEmpty(envUrl))
            config.ManagementUrl = envUrl;

        var envFormat = Environment.GetEnvironmentVariable("SCADALINK_FORMAT");
        if (!string.IsNullOrEmpty(envFormat))
            config.DefaultFormat = envFormat;

        // Credentials from environment variables only (never the config file).
        var envUsername = Environment.GetEnvironmentVariable("SCADALINK_USERNAME");
        if (!string.IsNullOrEmpty(envUsername))
            config.Username = envUsername;

        var envPassword = Environment.GetEnvironmentVariable("SCADALINK_PASSWORD");
        if (!string.IsNullOrEmpty(envPassword))
            config.Password = envPassword;

        return config;
    }

    private class CliConfigFile
    {
        public string? ManagementUrl { get; set; }
        public string? DefaultFormat { get; set; }
    }
}
