<?php

namespace App\Services;

use App\Models\SystemSetting;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;

/**
 * 系统设置服务类
 * 
 * 提供系统设置的业务逻辑处理
 */
class SystemSettingService
{
    /**
     * 缓存键名
     */
    private const CACHE_KEY = 'system_settings_grouped';

    /**
     * 缓存时间（秒）- 24小时
     */
    private const CACHE_TTL = 86400;

    /**
     * 获取按分组组织的所有系统设置
     * 
     * @return array<string, array> 按group分组的配置数组
     */
    public function getGroupedSettings(): array
    {
        return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function () {
            return SystemSetting::all()
                ->groupBy('group')
                ->map(function (Collection $settings) {
                    return $settings->map(function (SystemSetting $setting) {
                        return [
                            'id' => $setting->id,
                            'key' => $setting->key,
                            'value' => $setting->value,
                            'description' => $setting->description,
                            'is_public' => $setting->is_public,
                            'updated_at' => $setting->updated_at,
                        ];
                    })->values()->toArray();
                })
                ->toArray();
        });
    }

    /**
     * 批量更新系统设置
     * 
     * @param array $settings 配置数组，格式为 ['key' => 'value', ...]
     * @return void
     */
    public function updateSettings(array $settings): void
    {
        foreach ($settings as $key => $value) {
            SystemSetting::set($key, $value);
        }

        // 清除缓存
        $this->clearCache();
    }

    /**
     * 清除系统设置缓存
     * 
     * @return void
     */
    public function clearCache(): void
    {
        Cache::forget(self::CACHE_KEY);
    }
}
