using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace eSuite.API.Swagger;

internal class HasAllowAnonymousOperationsFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext ctx)
    {
        if (ctx.ApiDescription.ActionDescriptor is ControllerActionDescriptor descriptor)
        {
            // If not [AllowAnonymous] and [Authorize] on either the endpoint or the controller...
            if (!ctx.ApiDescription.CustomAttributes().Any((a) => a is AllowAnonymousAttribute))
            {
                operation.Security = new List<OpenApiSecurityRequirement>{
                    new OpenApiSecurityRequirement {
                        {
                            new OpenApiSecuritySchemeReference(
                                "Bearer",
                                ctx.Document,
                                null
                            ),
                            []
                        }
                    }};
            }
        }
    }
}