<?php

namespace MintyPHP\Module\Bookmarks\Providers;

use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\SessionProvider;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Bookmarks\Service\BookmarkService;

final class BookmarksSessionProvider implements SessionProvider
{
    private const SESSION_KEY = 'module.bookmarks.grouped';

    public function populate(array $user, AppContainer $container): void
    {
        $sessionStore = $container->get(SessionStoreInterface::class);
        if (!$sessionStore instanceof SessionStoreInterface) {
            return;
        }

        $userId = (int) ($user['id'] ?? 0);
        if ($userId <= 0) {
            $sessionStore->remove(self::SESSION_KEY);
            return;
        }

        $bookmarkService = $container->get(BookmarkService::class);
        if (!$bookmarkService instanceof BookmarkService) {
            return;
        }

        $sessionStore->set(self::SESSION_KEY, $bookmarkService->listGroupedForUser($userId));
    }

    public function clear(AppContainer $container): void
    {
        $sessionStore = $container->get(SessionStoreInterface::class);
        if ($sessionStore instanceof SessionStoreInterface) {
            $sessionStore->remove(self::SESSION_KEY);
        }
    }
}
