<?php

declare(strict_types=1);

namespace App\Shared\Infrastructure\Tenant;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final readonly class TenantDatabaseRequestSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private TenantDatabaseSwitcher $databaseSwitcher,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 255],
            KernelEvents::TERMINATE => 'onKernelTerminate',
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $tenant = $event->getRequest()->attributes->get('_tenant');
        if (!$tenant instanceof TenantConfig) {
            $this->databaseSwitcher->useDefaultDatabase();

            return;
        }

        $this->databaseSwitcher->useTenantDatabase($tenant->databaseUrl);
    }

    public function onKernelTerminate(): void
    {
        $this->databaseSwitcher->useDefaultDatabase();
    }
}
