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-rename
    // 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
    };

    /// <inheritdoc />
    // Returns a new default instance when the settings file is missing or fails to load/parse.
    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();
        }
    }

    /// <inheritdoc />
    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
        }
    }
}
