using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Results;

namespace TakeoutSaaS.Shared.Web.Filters;

/// <summary>
/// 模型验证过滤器：将模型验证错误统一为ApiResponse输出
/// </summary>
public sealed class ValidateModelAttribute : ActionFilterAttribute
{
    /// <summary>
    /// 在 Action 执行前拦截模型验证错误。
    /// </summary>
    /// <param name="context">执行上下文。</param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // 1. 模型验证未通过则返回 422
        if (!context.ModelState.IsValid)
        {
            var errors = context.ModelState
                .Where(kv => kv.Value?.Errors.Count > 0)
                .ToDictionary(
                    kv => kv.Key,
                    kv => kv.Value!.Errors.Select(e => string.IsNullOrWhiteSpace(e.ErrorMessage) ? "Invalid" : e.ErrorMessage).ToArray()
                );

            var response = ApiResponse<object>.Error(ErrorCodes.ValidationFailed, "一个或多个验证错误", errors);
            context.Result = new UnprocessableEntityObjectResult(response);
        }
    }
}
