using System.Text.Json;
using System.Text.Json.Serialization;

namespace IWS5.Autotest.IWS5.UiTests.Base
{
    public static class ConfigLoader
    {
        public static async Task<Configurations> LoadConfigurationsAsync()
        {
            var json = await File.ReadAllTextAsync("ConfigurationUi.json");
            var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            var config = JsonSerializer.Deserialize<Configurations>(json, options);

            if (config == null)
            {
                throw new Exception("Failed to load configuration.");
            }
            return config;
        }

        public static async Task<EnvironmentSettings> LoadEnvironmentSettingsAsync()
        {
            var config = await LoadConfigurationsAsync();

            var envSettings = config.Environment.ToLower() switch
            {
                "local" => config.Local,
                "prod" => config.Prod,
                _ => throw new Exception("Unknown environment specified in the configuration.")
            };

            await BrowserManager.LaunchBrowserAsync(envSettings.baseUrl);

            return envSettings;
        }
    }

    public class Configurations
    {
        [JsonPropertyName("environment")]
        public string Environment { get; set; }

        [JsonPropertyName("isHeadless")]
        public bool IsHeadless { get; set; }

        [JsonPropertyName("local")]
        public EnvironmentSettings Local { get; set; }

        [JsonPropertyName("prod")]
        public EnvironmentSettings Prod { get; set; }
    }

    public class EnvironmentSettings
    {
        [JsonPropertyName("baseUrl")]
        public string baseUrl { get; set; }

        [JsonPropertyName("username")]
        public string Username { get; set; }

        [JsonPropertyName("password")]
        public string Password { get; set; }

        [JsonPropertyName("logInPath")]
        public string LogInPath { get; set; }
    }
}
