<?php

namespace App\Http\Middleware;

use App\Models\Role;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RoleMiddleware
{
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (! $request->user()) {
            return redirect()->route('login');
        }

        $userRoleSlug = $request->user()->role;

        // Direct match against the allowed roles list
        if (in_array($userRoleSlug, $roles)) {
            return $next($request);
        }

        // Custom role: check if its parent_role matches any allowed role
        $roleModel = Role::where('slug', $userRoleSlug)->first();
        if ($roleModel && in_array($roleModel->parent_role, $roles)) {
            return $next($request);
        }

        abort(403, 'You do not have permission to access this page.');
    }
}
