<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });

        // Redirect to home with a toast when a video URL can't be resolved
        $this->renderable(function (NotFoundHttpException $e, $request) {
            $prev = $e->getPrevious();
            $isVideoRoute = str_starts_with($request->path(), 'videos/');

            if ($isVideoRoute && ($prev instanceof ModelNotFoundException || $e->getMessage() === '')) {
                return redirect('/')->with('toast_error', 'This video is no longer available.');
            }
        });
    }
}
