using System.Text.Json;
using System.Text.Json.Serialization;

namespace ReactorMaintenance.Simulation;

public static class LevelSerializer
{
    private const int c_CurrentVersion = 1;

    public static string Serialize(LevelState level)
    {
        return JsonSerializer.Serialize(new LevelFile {
            Version = c_CurrentVersion,
            Level = level
        }, Options);
    }

    public static LevelState Deserialize(string json)
    {
        var file = JsonSerializer.Deserialize<LevelFile>(json, Options) ?? throw new InvalidOperationException("Level file did not contain a level.");
        var level = file.Version switch {
            c_CurrentVersion => file.Level,
            _ => throw new InvalidOperationException($"Unsupported level file version {file.Version}.")
        };

        return level.Cells.Length != level.Width * level.Height ? throw new InvalidOperationException("Level cell count does not match its dimensions.") : level;
    }

    private static readonly JsonSerializerOptions Options = new() {
        WriteIndented = true,
        Converters = { new JsonStringEnumConverter() }
    };

    private sealed record LevelFile
    {
        public int Version { get; init; }
        public LevelState Level { get; init; } = new();
    }
}
