using System.Collections.Generic;
using System.Security.Claims;
using CMSMicroservice.Application.Common.Authorization;
using Microsoft.AspNetCore.Http;

namespace CMSMicroservice.Infrastructure.Services.Authorization;

/// <summary>
/// پیاده‌سازی سرویس مجوز — نقش‌ها از JWT Claims خوانده میشن
/// </summary>
public class PermissionService : IPermissionService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public PermissionService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public Task<IReadOnlyList<string>> GetUserRolesAsync(CancellationToken cancellationToken)
    {
        var user = _httpContextAccessor.HttpContext?.User;
        if (user?.Identity is not { IsAuthenticated: true })
            return Task.FromResult<IReadOnlyList<string>>(Array.Empty<string>());

        var roles = user.Claims
            .Where(c => c.Type == ClaimTypes.Role
                     || string.Equals(c.Type, "role", StringComparison.OrdinalIgnoreCase))
            .Select(c => c.Value)
            .Where(v => !string.IsNullOrWhiteSpace(v))
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToList();

        return Task.FromResult<IReadOnlyList<string>>(roles);
    }

    public async Task<bool> HasPermissionAsync(string permission, CancellationToken cancellationToken)
    {
        if (string.IsNullOrWhiteSpace(permission)) return true;

        var roles = await GetUserRolesAsync(cancellationToken);
        if (roles.Count == 0) return false;

        foreach (var role in roles)
        {
            if (RolePermissionConfig.HasPermission(role, permission))
                return true;
        }

        return false;
    }
}
