using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;

namespace NetworkResurrector.Api.Controllers
{
    [AllowAnonymous]
    [ApiExplorerSettings(IgnoreApi = true)]
    public class ErrorsController : ControllerBase
    {
        public ErrorsController()
        {
        }

        internal record Error(int Status, string Title, string Message = null);

        [Route("error")]
        public IActionResult HandleErrors()
        {
            var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
            var exception = context.Error;

            return exception switch
            {
                ValidationException => StatusCode(StatusCodes.Status404NotFound, new Error(StatusCodes.Status404NotFound, "Internal server error", exception.Message)),
                UnauthorizedAccessException => StatusCode(StatusCodes.Status401Unauthorized, new Error(StatusCodes.Status401Unauthorized, "Internal server error")),
                _ => StatusCode(StatusCodes.Status500InternalServerError, new Error(StatusCodes.Status500InternalServerError, "Internal server error")),
            };
        }
    }
}
