using adas_core.Authentication.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace adas_core.Authentication.Attributes;

public class AuthorizePermissionsAttribute(
    IUserService userService)
    : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;

        var userName = user.Identity?.Name ?? string.Empty;
        var displayIdHeader = context.HttpContext.Request.Headers["Displayid"];

        if (string.IsNullOrEmpty(displayIdHeader.ToString()))
        {
            context.Result = new NotFoundObjectResult("displayIdHeader not found reference id doesn't exist on header");
            return;
        }

        var userDao = userService.GetUserByUserName(userName).Result;

        if (userDao == null)
            context.Result = new NotFoundObjectResult("User not found on AuthorizePermissionsAttribute");
    }
}