<?php

declare(strict_types=1);

namespace Builder\Seo\Http\Middleware;

use Builder\Seo\Models\Redirect;
use Closure;
use Illuminate\Database\QueryException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class HandleRedirects
{
    public function handle(Request $request, Closure $next): Response
    {
        $path = '/'.rtrim(ltrim($request->path(), '/'), '/');

        try {
            /** @var Redirect|null $redirect */
            $redirect = Redirect::where('from', $path)->first();
        } catch (QueryException) {
            return $next($request);
        }

        if ($redirect instanceof Redirect) {
            return new RedirectResponse($redirect->to, $redirect->type->statusCode());
        }

        return $next($request);
    }
}
