<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use App\Exceptions\FacturapiRequestException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    // Redireccionador a Vistas de Errores HTTP comunes
    function render($request, Throwable $exception)
    {
        if ($exception instanceof FacturapiRequestException)
            return response()->json($exception->facturapiError, $exception->status);

        if ($exception instanceof HttpExceptionInterface && !$request->is('api/*')) {
            $statusCode = $exception->getStatusCode();

            switch ($statusCode) {
                case 404:
                    return response()->view('errors.404', [], 404);
                case 419:
                    return response()->view('errors.419', [], 419);
                case 429:
                    return response()->view('errors.429', [], 429);
                case 500:
                    return response()->view('errors.500', [], 500);
                case 503:
                    return response()->view('errors.503', [], 503);
                default:
                    return response()->view('errors.500', ['exception' => $exception], $statusCode);
            }
        }

        return parent::render($request, $exception);
    }
}
