<?php

declare(strict_types=1);

namespace Plugin\tnt_stabila_shop\src\Services;

use JTL\Cache\JTLCacheInterface;
use JTL\Shop;
use Plugin\tnt_stabila_shop\src\Enums\PluginSettings;
use Plugin\tnt_stabila_shop\src\Helper\Formatter;
use Plugin\tnt_stabila_shop\src\Helper\PerformanceBooster;
use Plugin\tnt_stabila_shop\src\Repositories\DatabaseRepository;
use Plugin\tnt_stabila_shop\src\Repositories\SessionRepository;

class SettingsService
{
    use Formatter;

    protected JTLCacheInterface $cache;

    public function __construct(
        protected DatabaseRepository $database,
        protected SessionRepository $session,
        JTLCacheInterface|null $cache = null
    ) {
        $this->cache = $cache ?? Shop::Container()->getCache();
    }

    /**
     * @return int|float|string|object|list<string>|null
     */
    public function getSetting(string $settingName): int|float|string|object|array|null
    {
        return $this->database->getSetting($settingName);
    }

    /**
     * @param object{name: string, type: string, defaultValue: string} $setting
     * @param int|float|string|object|list<string> $value
     */
    public function setSetting(object $setting, int|float|string|object|array $value): void
    {
        $this->database->setSetting($setting, $value);
    }

    public function canBeEnabled(string $settingName): bool
    {
        $setting = PluginSettings::fromJsonValue($settingName, 'name');
        if ($setting === null) {
            return false;
        }
        if ($settingName === 'performanceBooster') {
            $journalID = $this->cache->getActiveMethod()->getJournalID();
            if ($journalID !== 'null_journal' && $journalID !== 'sqlite_journal') {
                return false;
            }
        }

        return true;
    }

    /**
     * Toggles activation of the SQLite cache method.
     *
     * @return bool True if the cache method was successfully (de-)activated.
     */
    public function toggleSqLiteCache(int $activate): bool
    {
        if ($activate === 0) {
            $this->cache->flushAll();
            $performanceBooster = PerformanceBooster::getSQLiteCache();
            if (!$performanceBooster instanceof \SQLite3) {
                return false;
            }
            // cache db needs to be empty to do this
            $performanceBooster->exec('PRAGMA page_size = 32768;');
        }
        $option  = (object)[
            'cWert' => $activate === 1 ? 'sqlite' : 'null',
        ];
        $result1 = $this->database->update(
            'teinstellungen',
            'cName',
            'caching_method',
            $option
        );
        $option  = (object)[
            'cWert' => $activate === 1 ? 'Y' : 'N',
        ];
        $result2 = $this->database->update(
            'teinstellungen',
            'cName',
            'caching_activated',
            $option
        );

        return $result1 && $result2;
    }

    /**
     * @return bool True if the cache method is active and the plugin setting is true.
     */
    public function getPerformanceBoosterEnabled(): bool
    {
        $pluginSettingIsActive = (bool)($this->getSetting('performanceBooster') ?? 0);
        return $this->database->isSQLiteCacheActive() && $pluginSettingIsActive;
    }
}
