using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Service.BusinessFilter;

#region minimalapi 流程


public class UnifiedApiResultEndpointFilter(ILogger<UnifiedApiResultEndpointFilter> _logger) : IEndpointFilter
{

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        // 调用下一个过滤器或端点处理程序
        var result = await next(context);

        // 检查返回值类型
        if (result is null)
        {
            return ResponseOutput.NotOk("No data found."); // 处理 null 返回
        }

        // 如果返回的是元组
        if (result is ValueTuple<object, object> tuple)
        {
            return ResponseOutput.Ok(tuple.Item1, tuple.Item2);
        }

        if (result is IResponseOutput responseOutput)
        {      
            if (!string.IsNullOrWhiteSpace(responseOutput.LocalizedInfo))
            {
                //统一在这里记录国际化的日志信息
                _logger.LogWarning($"{responseOutput.LocalizedInfo}");
            }
            return result;
        }

        // 对于其他情况，直接返回结果
        return ResponseOutput.Ok(result);
    }

    private IResponseOutput WrapResponse(object? value)
    {
        // 处理元组的情况
        if (value is ValueTuple<object, object> tuple)
        {
            return ResponseOutput.Ok(tuple.Item1, tuple.Item2);
        }

        // 包装单个对象
        return ResponseOutput.Ok(value);
    }
}

#endregion