<?php

namespace App\Http\Middleware;

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

class CheckAdminRole
{
    /**
     * Handle an incoming request.
     * Usage: middleware('admin.role:superadmin') or middleware('admin.role:admin,superadmin')
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        $admin = auth()->guard('admin')->user();

        if (!$admin) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
            return redirect()->route('admin.login');
        }

        if (!$admin->is_active) {
            auth()->guard('admin')->logout();
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Account is disabled'], 403);
            }
            return redirect()->route('admin.login')
                ->withErrors(['email' => 'Your account has been disabled.']);
        }

        if (!empty($roles) && !in_array($admin->role, $roles)) {
            // Log the permission denied attempt
            AdminAuditLog::logAction(
                $admin,
                AdminAuditLog::ACTION_PERMISSION_DENIED,
                'route',
                null,
                null,
                ['attempted_route' => $request->route()->getName(), 'required_roles' => $roles]
            );

            if ($request->expectsJson()) {
                return response()->json(['error' => 'You do not have permission to access this resource'], 403);
            }
            return redirect()->route('dashboard')
                ->with('error', 'You do not have permission to access that page.');
        }

        return $next($request);
    }
}
