<?php

namespace Maestro\Core\Http\Middleware;

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

class ValidateSessionFingerprint
{
    /**
     * Handle an incoming request.
     * 
     * Protects against session hijacking by binding the session to the client's IP address
     * and User-Agent. A stolen cookie used from a different machine or browser is rejected.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $currentFingerprint = hash('sha256',
            $request->ip() . '|' . $request->userAgent()
        );

        $storedFingerprint = session('session_fingerprint');

        if ($storedFingerprint && $storedFingerprint !== $currentFingerprint) {
            Log::warning('Session fingerprint mismatch — possible session hijacking', [
                'user_id'    => $request->user()?->id,
                'stored_ip'  => session('session_ip'),
                'current_ip' => $request->ip(),
            ]);

            session()->invalidate();
            session()->regenerateToken();

            return response()->json([
                'message'      => 'Session invalid. Please log in again.',
                'force_reauth' => true,
            ], 401);
        }

        return $next($request);
    }
}
