using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Client.Shared;

namespace ZB.MOM.WW.OtOpcUa.Client.UI.Services;

/// <summary>
/// Persists user settings to a JSON file under LocalApplicationData.
/// </summary>
public sealed class JsonSettingsService : ISettingsService
{
    // ClientStoragePaths.GetRoot runs the one-shot legacy-folder migration so pre-#208
    // developer boxes pick up their existing settings.json on first launch post-rename.
    private static readonly string SettingsDir = ClientStoragePaths.GetRoot();

    private static readonly string SettingsPath = Path.Combine(SettingsDir, "settings.json");

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        WriteIndented = true
    };

    /// <summary>Loads user settings from the settings file.</summary>
    /// <returns>The loaded user settings, or a new default instance if load fails.</returns>
    public UserSettings Load()
    {
        try
        {
            if (!File.Exists(SettingsPath))
                return new UserSettings();

            var json = File.ReadAllText(SettingsPath);
            return JsonSerializer.Deserialize<UserSettings>(json, JsonOptions) ?? new UserSettings();
        }
        catch
        {
            return new UserSettings();
        }
    }

    /// <summary>Saves user settings to the settings file.</summary>
    /// <param name="settings">The user settings to save.</param>
    public void Save(UserSettings settings)
    {
        try
        {
            Directory.CreateDirectory(SettingsDir);
            var json = JsonSerializer.Serialize(settings, JsonOptions);
            File.WriteAllText(SettingsPath, json);
        }
        catch
        {
            // Best-effort save; don't crash the app
        }
    }
}
