using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using AipGateway.API.Service.Models;
using AipGateway.API.Service.Exceptions;

namespace AipGateway.API.Service.Filters
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger _logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            _logger = logger;
            _logger.LogError("ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc: ExceptionFilter");
        }

        public void OnException(ExceptionContext context)
        {
            ErrorResponse error = new();

            switch (context.Exception)
            {
                case ApiException aipException:
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    error = new ErrorResponse()
                    {
                        HttpCode = (int)HttpStatusCode.InternalServerError,
                        Message = "ddd",// Messages.GeneralErrorMessage,
                    };
                    break;
                default:
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    error = new ErrorResponse()
                    {
                        HttpCode = (int)HttpStatusCode.InternalServerError,
                        Message = "xxx",// Messages.GeneralErrorMessage,
                    };
                    break;
            }

            _logger.LogError(context.Exception.StackTrace);

            ResponseContent response = new ResponseContent()
            {
                ErrorResponse = error
            };

            context.Result = new ObjectResult(response);
            context.ExceptionHandled = true;
        }
    }

}


