<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ModuleOrPermissionMiddleware
{
    /**
     * 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, $moduleOrPermission, $guard = null)
    {
        $authGuard = app('auth')->guard($guard);

        if ($authGuard->guest()) {
            throw abort(401, 'User is not logged in');
        }

        $systemModules = $request->user()->currentRole->roleHasSystemModule()->with(['systemModule'])->get();

        $modules = $systemModules->map(function ($systemModule) {
            return $systemModule->systemModule->name;
        })->toArray();

        $userPermissions = $request->user()->permissions->pluck('name')->toArray();
        
        $currentRolePermissions = $request->user()->currentRole->roleHasPermission()->with(['permission'])->get()->map(function ($permission) {
            return $permission->permission->name;
        })->toArray();

        $guards = array_merge($modules, $userPermissions);

        $guards = array_merge($guards, $currentRolePermissions);

        $moduleOrPermissions = is_array($moduleOrPermission)
            ? $moduleOrPermission
            : explode('|', $moduleOrPermission);

        foreach ($moduleOrPermissions as $moduleOrPermission) {
            if (in_array($moduleOrPermission, $guards)) {
                return $next($request);
            }
        }

        return response()->json([
            'error' => 'Unauthorized',
            'message' => 'You are not authorized to perform this action',
            'data' => $guards
        ], 403);
    }
}
