<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdminSlug
{
    /**
     * @param  \Closure(\Illuminate\Http\Request): \Symfony\Component\HttpFoundation\Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $slug = (string) $request->route('adminSlug');
        $expected = 'admin';

        try {
            if (Schema::hasTable('settings')) {
                $expected = (string) setting('admin_slug', 'admin');
            }
        } catch (\Throwable $exception) {
            $expected = 'admin';
        }

        if ($slug !== $expected) {
            abort(404);
        }

        return $next($request);
    }
}
