using System.Text.Json;

namespace RolemasterDb.ImportTool;

public sealed class CriticalImportManifestLoader
{
    public CriticalImportManifest Load(string manifestPath)
    {
        if (!File.Exists(manifestPath))
        {
            throw new FileNotFoundException("The critical import manifest could not be found.", manifestPath);
        }

        var manifest = JsonSerializer.Deserialize<CriticalImportManifest>(
            File.ReadAllText(manifestPath),
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

        if (manifest is null || manifest.Tables.Count == 0)
        {
            throw new InvalidOperationException("The critical import manifest is empty.");
        }

        if (manifest.Tables.Any(item => string.IsNullOrWhiteSpace(item.Slug)))
        {
            throw new InvalidOperationException("Each manifest entry must declare a slug.");
        }

        return manifest;
    }
}
