using System.Text.Json;

namespace AutorentWinForms;

public static class AppSettings
{
    public static string LoadConnectionString()
    {
        var env = Environment.GetEnvironmentVariable("AUTORENT_CONNECTION_STRING");
        if (!string.IsNullOrWhiteSpace(env))
            return env;

        var file = Path.Combine(AppContext.BaseDirectory, "dbsettings.json");
        if (!File.Exists(file))
            file = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "dbsettings.json"));

        if (!File.Exists(file))
            throw new InvalidOperationException("Не найден dbsettings.json и не задана переменная AUTORENT_CONNECTION_STRING.");

        var json = File.ReadAllText(file);
        var settings = JsonSerializer.Deserialize<DbSettings>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
        if (string.IsNullOrWhiteSpace(settings?.ConnectionString))
            throw new InvalidOperationException("В dbsettings.json не задана строка ConnectionString.");

        return settings.ConnectionString;
    }

    private sealed class DbSettings
    {
        public string? ConnectionString { get; set; }
    }
}
