<?php

namespace App\Http\Middleware;

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

class EnsureAdminRoleAccess
{
    public function handle(Request $request, Closure $next, string ...$allowedRoles): Response
    {
        if (! Auth::check()) {
            return redirect()->route('admin.logindata');
        }

        if ($allowedRoles === []) {
            return $next($request);
        }

        $currentRole = $this->resolveRole((int) (Auth::user()->usertype ?? 0));

        if (! in_array($currentRole, $allowedRoles, true)) {
            return redirect()->route('admin.dashboard')
                ->with('message', 'You are not allowed to access this area.');
        }

        return $next($request);
    }

    private function resolveRole(int $userType): string
    {
        return match ($userType) {
            1 => 'institute',
            3 => 'school',
            5 => 'blocked',
            4 => 'student',
            default => 'platform',
        };
    }
}
