<?php

namespace MintyPHP\Module\AddressBook\Providers;

use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\SessionProvider;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Service\User\UserTenantContextService;

/**
 * Populates session with department-by-tenant hierarchy data used by the
 * address book aside panel.
 */
final class AddressBookSessionProvider implements SessionProvider
{
    public function populate(array $user, AppContainer $container): void
    {
        $userId = (int) ($user['id'] ?? 0);
        if ($userId <= 0) {
            unset($_SESSION['module.addressbook.departments_by_tenant']);
            return;
        }

        $tenantContext = $container->get(UserTenantContextService::class);
        $sessionStore = $container->get(SessionStoreInterface::class);
        if (!$tenantContext instanceof UserTenantContextService || !$sessionStore instanceof SessionStoreInterface) {
            return;
        }

        $sessionStore->set(
            'module.addressbook.departments_by_tenant',
            $tenantContext->getAvailableDepartmentsByTenant($userId)
        );
    }

    public function clear(): void
    {
        unset($_SESSION['module.addressbook.departments_by_tenant']);
    }
}
