<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\SystemConfig;
use App\Enum\SystemSettingKey;
use Doctrine\ORM\EntityManagerInterface;

/**
 * @extends AbstractRepository<SystemConfig>
 */
class SystemConfigRepository extends AbstractRepository
{
    public function __construct(EntityManagerInterface $entityManager)
    {
        parent::__construct($entityManager, $entityManager->getClassMetadata(SystemConfig::class));
    }

    public function findByKey(SystemSettingKey $key): SystemConfig
    {
        $config = $this->findOneBy([
            'key' => $key->value,
        ]);
        if (!($config instanceof SystemConfig)) {
            $config = new SystemConfig($key, SystemSettingKey::getDefaultValue($key));
            $this->save($config);
        }
        return $config;
    }

    public function getValue(SystemSettingKey $key, string $default = ''): string
    {
        $config = $this->findByKey($key);
        return ($config instanceof SystemConfig) ? $config->getValue() : $default;
    }

    public function setValue(SystemSettingKey $key, string $value): void
    {
        $config = $this->findByKey($key);

        if ($config instanceof SystemConfig) {
            $config->setValue($value);
        } else {
            $config = new SystemConfig($key, $value);
        }
        $this->save($config);
    }
}
