<?hh // strict

namespace App\Services;

use App\Models\Tenant;
use Psr\Http\Message\ServerRequestInterface;

class TenantResolver
{
    /**
     * Resolve the tenant based on the request
     */
    public function resolveTenant(ServerRequestInterface $request): ?Tenant
    {
        $host = $request->getUri()->getHost();
        $path = $request->getUri()->getPath();
        
        // Try to extract tenant from subdomain
        // Format: tenant.merchantsofhope.org
        $hostParts = explode('.', $host);
        if (count($hostParts) >= 3) {
            $subdomain = $hostParts[0];
            return $this->findTenantBySubdomain($subdomain);
        }
        
        // Alternatively, look for tenant in path
        // Format: merchantsofhope.org/tenant-name
        $pathParts = explode('/', trim($path, '/'));
        if (!empty($pathParts[0])) {
            return $this->findTenantBySubdomain($pathParts[0]);
        }
        
        // Default to a global tenant if none found
        return null;
    }
    
    /**
     * Find tenant by subdomain in the database
     */
    private function findTenantBySubdomain(string $subdomain): ?Tenant
    {
        // This would normally query the database
        // For now, we'll return a mock tenant if subdomain exists
        if (!empty($subdomain)) {
            return new Tenant(
                id: 'tenant-' . $subdomain,
                name: ucfirst($subdomain) . ' Tenant',
                subdomain: $subdomain,
                isActive: true
            );
        }
        
        return null;
    }
}