<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\SystemConfig;
use App\Enum\SystemSettingKey;
use App\Repository\SystemConfigRepository;
use InvalidArgumentException;

readonly class ConfigurationService
{
    public function __construct(
        private SystemConfigRepository $systemConfigRepository,
    ) {}

    /**
     * Get all configuration entries
     *
     * @return SystemConfig[]
     */
    public function getAllConfigs(): array
    {
        return $this->systemConfigRepository->findAll();
    }

    public function getConfigValue(SystemSettingKey $key, string $default = ''): string
    {
        return $this->systemConfigRepository->getValue($key, $default);
    }

    public function setConfigValue(SystemSettingKey $key, string $value): void
    {
        $this->systemConfigRepository->setValue($key, $value);
    }

    public function getConfigByKey(SystemSettingKey $key): SystemConfig
    {
        return $this->systemConfigRepository->findByKey($key);
    }

    public function createConfig(SystemSettingKey $key, string $value): SystemConfig
    {
        if ($this->systemConfigRepository->findByKey($key) instanceof SystemConfig) {
            throw new InvalidArgumentException("A configuration with the key '{$key->value}' already exists");
        }

        $config = new SystemConfig($key, $value);
        $this->systemConfigRepository->save($config);

        return $config;
    }

    public function updateConfig(SystemConfig $config, string $value): SystemConfig
    {
        if ($value !== '') {
            $config->setValue($value);
        }
        $this->systemConfigRepository->save($config);

        return $config;
    }

    public function resetAllConfigs(): void
    {
        foreach (SystemSettingKey::cases() as $key) {
            $this->setDefaultValue($key);
        }
    }

    public function setDefaultValue(SystemSettingKey $key): void
    {
        $this->setConfigValue($key, SystemSettingKey::getDefaultValue($key));
    }
}
