<?php

declare(strict_types=1);

namespace App\SuperAdmin\Application\Command\SwitchTenant;

use App\Shared\Domain\Tenant\TenantId;
use App\SuperAdmin\Domain\Exception\EstablishmentIntrouvableException;
use App\SuperAdmin\Domain\Repository\EstablishmentRepository;
use App\SuperAdmin\Infrastructure\Security\SuperAdminTenantContext;

final readonly class SwitchTenantHandler
{
    public function __construct(
        private EstablishmentRepository $establishmentRepository,
        private SuperAdminTenantContext $superAdminTenantContext,
    ) {
    }

    public function __invoke(SwitchTenantCommand $command): void
    {
        $tenantId = TenantId::fromString($command->tenantId);

        $establishment = $this->establishmentRepository->findByTenantId($tenantId);

        if ($establishment === null) {
            throw EstablishmentIntrouvableException::avecTenantId($tenantId);
        }

        $this->superAdminTenantContext->switchTo($tenantId);
    }
}
