<?php

namespace App\Http\Middleware;

use App\Support\RequestContext;
use App\Support\TenantResolver;

class ResolveTenant
{
    public function __construct(
        private readonly TenantResolver $tenantResolver,
        private readonly RequestContext $requestContext
    ) {
    }

    public function handle(object $request, callable $next): mixed
    {
        $host = method_exists($request, 'getHost')
            ? (string) $request->getHost()
            : '';

        $tenant = $this->tenantResolver->resolveFromHost($host);

        if ($tenant !== null) {
            $this->requestContext->setTenant(
                $tenant['tenant_id'],
                $tenant['tenant_key']
            );
        }

        return $next($request);
    }
}
