<?php

namespace MintyPHP\Service\Auth;

use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\User\UserSavedFilterService;
use MintyPHP\Service\User\UserTenantContextService;

class AuthSessionTenantContextService
{
    public function __construct(
        private readonly UserTenantContextService $userTenantContextService,
        private readonly UserSavedFilterService $savedFilterService,
        private readonly SessionStoreInterface $sessionStore
    ) {
    }

    public function hydrateForUser(int $userId): void
    {
        if ($userId <= 0) {
            return;
        }

        $availableTenants = $this->userTenantContextService->getAvailableTenants($userId);
        $this->sessionStore->set('available_tenants', $availableTenants);
        $this->sessionStore->set('available_departments_by_tenant', $this->userTenantContextService->getAvailableDepartmentsByTenant($userId));
        $this->sessionStore->set('address_book_saved_filters', $this->savedFilterService->listForAddressBook($userId));

        if (!$availableTenants) {
            $this->sessionStore->set('no_active_tenant', true);
            $this->sessionStore->remove('current_tenant');
            return;
        }

        $this->sessionStore->set('no_active_tenant', false);

        // If the DB has no preferred tenant stored, fall back to the first available one.
        $currentTenant = $this->userTenantContextService->getCurrentTenant($userId);
        if (!$currentTenant) {
            $currentTenant = $availableTenants[0];
        }

        if ($currentTenant) {
            $this->sessionStore->set('current_tenant', $currentTenant);
        }
    }
}
