using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using TeamsISO.Engine.Domain;

namespace TeamsISO.Engine.Persistence;

/// <summary>
/// Loads and saves <see cref="EngineConfig"/> as JSON.
/// Writes are atomic: serialize to a temp file in the same directory, then <c>File.Move</c> with overwrite.
/// </summary>
public sealed class ConfigStore
{
    private static readonly JsonSerializerOptions Options = new()
    {
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        Converters = { new JsonStringEnumConverter() }
    };

    private readonly string _path;
    private readonly ILogger<ConfigStore> _logger;

    public ConfigStore(string path, ILogger<ConfigStore> logger)
    {
        _path = path;
        _logger = logger;
    }

    public EngineConfig Load()
    {
        if (!File.Exists(_path))
        {
            _logger.LogInformation("Config file not found at {Path}; using defaults.", _path);
            return EngineConfig.Default;
        }

        try
        {
            var json = File.ReadAllText(_path);
            var loaded = JsonSerializer.Deserialize<EngineConfig>(json, Options);
            return loaded ?? EngineConfig.Default;
        }
        catch (JsonException ex)
        {
            _logger.LogWarning(ex, "Config file at {Path} is not valid JSON; using defaults.", _path);
            return EngineConfig.Default;
        }
    }

    public void Save(EngineConfig config)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
        var temp = _path + ".tmp";
        var json = JsonSerializer.Serialize(config, Options);
        File.WriteAllText(temp, json);
        File.Move(temp, _path, overwrite: true);
    }
}
