using System.Text.Json;

namespace LocationTrackerApp.Services;

/// <summary>
/// Provides configuration services for the application
/// </summary>
public class ConfigurationService : IConfigurationService
{
    private readonly string _googleMapsApiKey;

    /// <summary>
    /// Initializes a new instance of the ConfigurationService
    /// </summary>
    public ConfigurationService()
    {
        _googleMapsApiKey = LoadGoogleMapsApiKey();
    }

    /// <summary>
    /// Gets the Google Maps API key
    /// </summary>
    public string GetGoogleMapsApiKey()
    {
        return _googleMapsApiKey;
    }

    /// <summary>
    /// Loads the Google Maps API key from configuration
    /// </summary>
    private string LoadGoogleMapsApiKey()
    {
        try
        {
            // First, try to get from environment variable
            var envApiKey = Environment.GetEnvironmentVariable("GoogleMapsApiKey");
            if (!string.IsNullOrEmpty(envApiKey) && envApiKey != "YOUR_ACTUAL_API_KEY_HERE")
            {
                return envApiKey;
            }

            // Then try to load from appsettings.json
            var configPath = Path.Combine(FileSystem.AppDataDirectory, "appsettings.json");
            if (File.Exists(configPath))
            {
                var json = File.ReadAllText(configPath);
                var config = JsonSerializer.Deserialize<JsonElement>(json);
                
                if (config.TryGetProperty("GoogleMaps", out var googleMaps) &&
                    googleMaps.TryGetProperty("ApiKey", out var apiKeyElement))
                {
                    var apiKey = apiKeyElement.GetString();
                    if (!string.IsNullOrEmpty(apiKey) && apiKey != "YOUR_ACTUAL_API_KEY_HERE")
                    {
                        return apiKey;
                    }
                }
            }

            // Fallback to default demo key
            return "AIzaSyDemoKeyForDevelopment123456789";
        }
        catch (Exception)
        {
            // Return demo key if anything goes wrong
            return "AIzaSyDemoKeyForDevelopment123456789";
        }
    }
}
