using System;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

namespace Tornado3_2026Election.Persistence;

public sealed class AppStateStore
{
    private static readonly JsonSerializerOptions SerializerOptions = new()
    {
        WriteIndented = true
    };

    public string FilePath { get; } = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
        "Tornado3_2026Election",
        "app-state.json");

    public async Task<AppState?> LoadAsync()
    {
        if (!File.Exists(FilePath))
        {
            return null;
        }

        await using var stream = File.OpenRead(FilePath);
        return await JsonSerializer.DeserializeAsync<AppState>(stream, SerializerOptions).ConfigureAwait(false);
    }

    public async Task SaveAsync(AppState state)
    {
        var directory = Path.GetDirectoryName(FilePath);
        if (!string.IsNullOrWhiteSpace(directory) && !Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }

        await using var stream = File.Create(FilePath);
        await JsonSerializer.SerializeAsync(stream, state, SerializerOptions).ConfigureAwait(false);
    }
}
