using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using OpenWarehouse.auth.Common.ApiInterfeiceLib;
using OpenWarehouse.auth.lib;

namespace OpenWarehouse.warehouse.api.Common.CustimIdentifyManager;

public class HasPrivilage : Attribute, IAsyncAuthorizationFilter
{
    public ServicePrivilage Privilage;

    public HasPrivilage(ServicePrivilage privilage)
    {
        Privilage = privilage;
    }
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
       context.HttpContext.Request.Headers.TryGetValue("Authorization", out var token);

       var sToken = token.ToString();
        
       if (sToken == "")  context.Result = new UnauthorizedResult();
       
        var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
        var handler = new AuthTokenHandler(sToken);
        var httpClient = new HttpClient(handler);
        var client = new OpenWarehouseAuthClient(config["Auth:Url"], httpClient);
        
        var privilage = await client.GetUserPrivilagesAsync();
        if (privilage is {Count: 0} && !privilage.Any(s =>  s.Equals(Privilage.GetName())))
        {
            context.Result = new ForbidResult();
        }
        
        return;
    }
}