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

namespace SIGCM2.Application.Common;

/// <summary>
/// UDT-009: Overrides explícitos sobre permisos heredados del rol.
/// Shape: { "grant": [...], "deny": [...] }
/// </summary>
public sealed record PermisosOverride(
    [property: JsonPropertyName("grant")] IReadOnlyList<string> Grant,
    [property: JsonPropertyName("deny")] IReadOnlyList<string> Deny)
{
    /// <summary>No overrides — empty grant and deny.</summary>
    public static readonly PermisosOverride Empty =
        new(Array.Empty<string>(), Array.Empty<string>());

    private static readonly JsonSerializerOptions Options = new()
    {
        PropertyNameCaseInsensitive = true,
    };

    /// <summary>
    /// Parses <paramref name="json"/> tolerantly:
    /// - null / "" / whitespace → Empty
    /// - starts with '[' (legacy '[]' or '["*"]') → Empty (backward compat)
    /// - valid JSON object with grant/deny → parsed record
    /// - malformed or wrong-shape JSON → Empty (tolerant in runtime)
    /// </summary>
    public static PermisosOverride FromJson(string? json)
    {
        if (string.IsNullOrWhiteSpace(json))
            return Empty;

        var trimmed = json.Trim();

        // Legacy: '[]' or '["*"]' — array shape, treat as no overrides
        if (trimmed.StartsWith('['))
            return Empty;

        try
        {
            var parsed = JsonSerializer.Deserialize<PermisosOverride>(trimmed, Options);
            if (parsed is null)
                return Empty;

            return new PermisosOverride(
                parsed.Grant ?? Array.Empty<string>(),
                parsed.Deny ?? Array.Empty<string>());
        }
        catch (JsonException)
        {
            // Tolerant: malformed JSON → Empty (protects authorization handler)
            return Empty;
        }
    }

    /// <summary>Serializes to canonical JSON shape.</summary>
    public string ToJson() => JsonSerializer.Serialize(this, Options);
}
