<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Service;

use Paysera\PrestashopPayments\Enum\ConfigurationKey;
use Paysera\PrestashopPayments\Provider\TranslationsDataProvider;
use Psr\Log\LoggerInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

class TranslationFileRefresher
{
    private const REFRESH_INTERVAL = 604800;

    public function __construct(
        private TranslationsDataProvider $translationsDataProvider,
        private XliffFileGenerator $xliffFileGenerator,
        private LoggerInterface $logger,
        private CmsToolsFacade $cmsToolsFacade
    ) {
    }

    public function generateTranslationFiles(): bool
    {
        try {
            $translationsData = $this->translationsDataProvider->getTranslationsData();

            if ($translationsData === null) {
                $this->logger->warning('Failed to fetch translations data');

                return false;
            }

            $this->xliffFileGenerator->generate($translationsData);
            $this->cmsToolsFacade->clearSf2Cache();
            $this->updateLastRefreshTime();

            return true;
        } catch (\Throwable $exception) {
            $this->logger->error('Translation file generation failed', [
                'exception' => $exception->getMessage(),
                'code' => $exception->getCode(),
            ]);

            return false;
        }
    }

    public function shouldRefresh(): bool
    {
        $lastRefresh = \Configuration::get(ConfigurationKey::TRANSLATIONS_LAST_REFRESH);
        if ($lastRefresh === false) {
            return true;
        }

        $timeSinceRefresh = time() - (int) $lastRefresh;

        return $timeSinceRefresh >= self::REFRESH_INTERVAL;
    }

    public function refreshIfNeeded(): bool
    {
        if (!$this->shouldRefresh()) {
            return false;
        }

        return $this->generateTranslationFiles();
    }

    private function updateLastRefreshTime(): void
    {
        \Configuration::updateValue(ConfigurationKey::TRANSLATIONS_LAST_REFRESH, (string) time());
    }
}
