namespace SharepointToolbox.Core.Models;

/// <summary>
/// Summary counts of permission entries grouped by risk level.
/// Displayed in the summary panel when simplified mode is active.
/// </summary>
public record PermissionSummary(
    /// <summary>Label for this group (e.g. "High Risk", "Read Only").</summary>
    string Label,
    /// <summary>The risk level this group represents.</summary>
    RiskLevel RiskLevel,
    /// <summary>Number of permission entries at this risk level.</summary>
    int Count,
    /// <summary>Number of distinct users at this risk level.</summary>
    int DistinctUsers
);

/// <summary>
/// Computes PermissionSummary groups from SimplifiedPermissionEntry collections.
/// </summary>
public static class PermissionSummaryBuilder
{
    /// <summary>
    /// Risk level display labels.
    /// </summary>
    private static readonly Dictionary<RiskLevel, string> Labels = new()
    {
        [RiskLevel.High] = "High Risk",
        [RiskLevel.Medium] = "Medium Risk",
        [RiskLevel.Low] = "Low Risk",
        [RiskLevel.ReadOnly] = "Read Only",
    };

    /// <summary>
    /// Builds summary counts grouped by risk level from a collection of simplified entries.
    /// Always returns all 4 risk levels, even if count is 0, for consistent UI binding.
    /// </summary>
    public static IReadOnlyList<PermissionSummary> Build(
        IEnumerable<SimplifiedPermissionEntry> entries)
    {
        var grouped = entries
            .GroupBy(e => e.RiskLevel)
            .ToDictionary(g => g.Key, g => g.ToList());

        return Enum.GetValues<RiskLevel>()
            .Select(level =>
            {
                var items = grouped.GetValueOrDefault(level, new List<SimplifiedPermissionEntry>());
                var distinctUsers = items
                    .SelectMany(e => e.UserLogins.Split(';', StringSplitOptions.RemoveEmptyEntries))
                    .Select(u => u.Trim())
                    .Where(u => u.Length > 0)
                    .Distinct(StringComparer.OrdinalIgnoreCase)
                    .Count();

                return new PermissionSummary(
                    Label: Labels[level],
                    RiskLevel: level,
                    Count: items.Count,
                    DistinctUsers: distinctUsers);
            })
            .ToList();
    }
}
