using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Serilog;
using System.Diagnostics.CodeAnalysis;
using User.Insight.Tracker.DataContracts;

namespace User.Insight.Tracker.Common
{
    [ExcludeFromCodeCoverage]
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            Log.Logger.Error(context.Exception, context.Exception.Message);
            Payload<string> res = new Payload<string>();
            res.Message = context.Exception.Message;
            res.IsSuccess = false;
            context.Result = new JsonResult(res);
            if (context.Exception is UnauthorisedException)
                context.HttpContext.Response.StatusCode = 200;
            else if (context.Exception is DataValidationException)
                context.HttpContext.Response.StatusCode = 200;
            else if (context.Exception is RoleChangedException roleEx)
                context.HttpContext.Response.StatusCode = roleEx.StatusCode;
            else
                context.HttpContext.Response.StatusCode = 500;
            base.OnException(context);
        }
    }
}
