<?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;
use App\Services\Auth\RoleBasedAccessService;

class WarehousePermissionMiddleware
{
    protected $accessService;

    public function __construct(RoleBasedAccessService $accessService)
    {
        $this->accessService = $accessService;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $permission
     */
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        // Check if user is authenticated
        if (!Auth::check()) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Authentication required'], 401);
            }
            return redirect()->route('admin.login')->with('error', 'Please log in to access this page.');
        }

        $user = Auth::user();

        // Check if user has the required permission using the service
        if (!$this->accessService->hasPermission($user, $permission)) {
            // Log the access attempt for security monitoring
            Log::warning('Unauthorized warehouse access attempt', [
                'user_id' => $user->id,
                'email' => $user->email,
                'permission' => $permission,
                'route' => $request->route()?->getName(),
                'url' => $request->fullUrl(),
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent()
            ]);

            if ($request->expectsJson()) {
                return response()->json([
                    'error' => 'Insufficient permissions',
                    'message' => 'You do not have permission to access this warehouse resource.',
                    'required_permission' => $permission
                ], 403);
            }

            // Check if user has any warehouse access at all
            if (!$this->accessService->hasWarehouseAccess($user)) {
                abort(403, 'You do not have access to the warehouse system. Please contact your administrator.');
            }

            abort(403, 'You do not have permission to access this warehouse feature. Required permission: ' . $permission);
        }

        return $next($request);
    }
}