using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppLibs.Libs
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class AsyncGateAttribute : Attribute, IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(
            ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            var vr = context.HttpContext.Request.Query["vr"].ToString();

            // Nếu có vr=cAsync hoặc vr=lAsync => cho chạy action (logic nặng)
            if (vr == "cAsync" || vr == "lAsync")
            {
                await next();
                return;
            }

            // Không có vr => return ViewAsync ngay, bỏ qua action
            if (context.Controller is Controller c)
            {
                var result = await ControllerExtensions.ViewAsync(c);
                context.Result = result; // short-circuit
                return;
            }

            context.Result = new NotFoundResult();
        }
    }
}
