<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class EnsureArtworkMaturityAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->user('controlpanel') !== null) {
            return $next($request);
        }

        $user = $request->user();
        $role = strtolower((string) ($user?->role ?? ''));

        if (in_array($role, ['admin', 'moderator'], true)) {
            return $next($request);
        }

        if (! $request->expectsJson() && route('cp.login', absolute: false) !== null) {
            return redirect()->route('cp.login');
        }

        abort(Response::HTTP_FORBIDDEN, 'Forbidden.');
    }
}