<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

class EnsureCreatorAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if ($user === null) {
            abort(403, 'Authentication required.');
        }

        $role = strtolower((string) ($user->role ?? 'user'));
        $isCreatorRole = in_array($role, ['creator', 'user', 'admin', 'moderator', 'mod'], true);

        if (! $isCreatorRole || (property_exists($user, 'is_active') && $user->is_active === false)) {
            abort(403, 'Creator access is required.');
        }

        return $next($request);
    }
}
