<?php

namespace App\Http\Middleware;

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

class SuperAdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->is('super-admin/login') || $request->is('super-admin/register')) {
            return $next($request);
        }

        if (! Auth::check()) {
            abort(403, 'Nicht angemeldet.');
        }

        $user = Auth::user();
        Log::info('SuperAdminAuth: User ID '.$user->id.', role: '.$user->role);

        if (! $user->isSuperAdmin()) {
            abort(403, 'Zugriff nur für SuperAdmin. User ID: '.$user->id.', Role: '.$user->role);
        }

        return $next($request);
    }
}
