<?php

namespace Opentalent\OtCore\Cache;

use Opentalent\OtCore\Website\OtPageRepository;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Cache\CacheManager;

class OtCacheManager
{
    public function __construct(
        private readonly OtPageRepository $otPageRepository,
        private readonly ConnectionPool $connectionPool,
        private readonly CacheManager $cacheManager
    ) {}

    /**
     * Clears the page cache
     *
     * @param int $pageUid
     */
    public static function clearPageCache(int $pageUid) {
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
        $cacheManager->flushCachesInGroupByTag(
            'pages',
            'pageId_' . $pageUid
        );
    }

    /**
     * Clears cache for each page of the site
     *
     * @param int $pageUid
     * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
     */
    public function clearSiteCache(int $pageUid, bool $clearAll = false) {

        $rootPage = $this->otPageRepository->getRootPageFor($pageUid);
        $pages = $this->otPageRepository->getAllSubpagesForPage($rootPage['uid']);
        $pages[] = $rootPage;

        $tags = array_map(function ($page) {
            return 'pageId_' . $page['uid'];
        }, $pages);

        if ($clearAll) {
            $this->cacheManager->flushCachesByTags($tags);
        } else {
            $this->cacheManager->flushCachesInGroupByTags('pages', $tags);
        }

        // << BUGFIX: without this, the fluid templates caches are not cleared
        $cnn = $this->connectionPool->getConnectionByName('Default');
        $cnn->beginTransaction();
        $sql = "update typo3.cache_hash h inner join typo3.cache_hash_tags t on h.id = t.id
                set h.expires = 0
                where t.tag = 'ident_TS_TEMPLATE';";
        $stmt = $cnn->prepare($sql);
        $stmt->executeQuery();
        $cnn->commit();
        // >>
    }

    /**
     * Clears cache
     *
     * @param bool $clearAll if true, all caches will be cleared, and not only the frontend one
     */
    public static function clearCache($clearAll) {
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);

        if ($clearAll) {
            $cacheManager->flushCachesInGroup('pages');
        } else {
            $cacheManager->flushCaches();
        }
    }

    /**
     * Clear cache framework and opcode caches
     *
     * @see TYPO3\CMS\Install\Controller\MaintenanceController
     */
    public static function clearAllCache()
    {
        $cacheManager = GeneralUtility::makeInstance(CacheManager::class);
        $cacheManager->flushCaches();
//        GeneralUtility::makeInstance(ClearCacheService::class)->clearAll();
//        GeneralUtility::makeInstance(OpcodeCacheService::class)->clearAllActive();
    }
}
