<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MahasiswaMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $memoryStart = memory_get_usage();
        
        if (!Auth::check()) {
            abort(403, 'Unauthorized');
        }

        if (Auth::user()->role !== 'mahasiswa') {
            abort(403, 'Unauthorized');
        }

        $response = $next($request);

        // Log memory usage
        $memoryUsed = (memory_get_usage() - $memoryStart)/1024/1024;
        if ($memoryUsed > 50) { // Jika > 50MB
            \Log::warning("High memory usage in MahasiswaMiddleware: {$memoryUsed}MB");
        }

        return $response;
    }
}
