<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Routing\Exceptions\InvalidSignatureException;

class HandleInvalidSignedUrl
{
    public function handle(Request $request, Closure $next)
    {
        try {
            return $next($request);
        } catch (InvalidSignatureException $exception) {
            if ($request->expectsJson()) {
                throw $exception;
            }

            if ($this->isVerificationRoute($request)) {
                $request->session()->flash('verification', [
                    'status' => 'error',
                    'title' => __('auth.verification.expired_title'),
                    'message' => __('auth.verification.expired_message'),
                ]);

                return redirect()->route('verification.notice');
            }

            throw $exception;
        }
    }

    private function isVerificationRoute(Request $request): bool
    {
        if ($request->route()?->getName() === 'verification.verify') {
            return true;
        }

        return str_starts_with($request->path(), 'verify-email/');
    }
}
