<?hh // strict

namespace App\Middleware;

use App\Services\TenantResolver;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Psr7\Response;

class TenantMiddleware implements MiddlewareInterface
{
    private TenantResolver $tenantResolver;
    
    public function __construct(TenantResolver $tenantResolver)
    {
        $this->tenantResolver = $tenantResolver;
    }
    
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Resolve the current tenant
        $tenant = $this->tenantResolver->resolveTenant($request);
        
        // Attach the tenant to the request attributes
        $request = $request->withAttribute('tenant', $tenant);
        
        // If we have a tenant, verify it's active
        if ($tenant !== null) {
            if (!$tenant->getIsActive()) {
                $response = new Response();
                $response->getBody()->write(json_encode([
                    'error' => 'Tenant is inactive',
                    'message' => 'This tenant account is currently inactive.'
                ]));
                return $response
                    ->withHeader('Content-Type', 'application/json')
                    ->withStatus(403);
            }
            
            // Set tenant-specific headers
            $response = $handler->handle($request);
            return $response->withAddedHeader('X-Tenant-ID', $tenant->getId());
        }
        
        // If no tenant found, we might want to return an error
        // Or provide a default experience
        $response = $handler->handle($request);
        return $response->withAddedHeader('X-Tenant-ID', 'default');
    }
}