<?php

namespace App\Http\Middleware;

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

/** Authenticated scan log listing — staff roles (legacy RFID log screen). */
class EnsureBadgeScanLogsAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var User|null $user */
        $user = Auth::user();
        if (! $user) {
            return response()->json(['message' => 'Unauthorized.'], 401);
        }

        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

        $allowed = [
            'administrator', 'admin', 'principal', 'vice_principal', 'vice-principal',
            'teacher', 'teacher_assistant',
        ];

        foreach ($allowed as $role) {
            if (in_array($role, $roles, true)) {
                return $next($request);
            }
        }

        return response()->json(['message' => 'Forbidden.'], 403);
    }
}
