<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ScopeSessionsIfStarted
{
    private const TENANT_ID_KEY = '_tenant_id';

    public function handle(Request $request, Closure $next): Response
    {
        if (!$request->hasSession() || !tenancy()->initialized) {
            return $next($request);
        }

        $session = $request->session();
        $tenantKey = tenant()->getTenantKey();

        if (!$session->has(self::TENANT_ID_KEY)) {
            $session->put(self::TENANT_ID_KEY, $tenantKey);
        } elseif ((string) $session->get(self::TENANT_ID_KEY) !== (string) $tenantKey) {
            $session->flush();
            $session->regenerate();
            $session->put(self::TENANT_ID_KEY, $tenantKey);
        }

        return $next($request);
    }
}
