<?php

namespace Kylin\Settings\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Settings\Models\Setting;
use Kylin\Settings\Services\SettingsService;

/**
 * 系统设置控制器
 *
 * 提供系统配置的读取和更新 API。
 *
 * 合规要求：
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.1，使用 SettingPolicy 控制访问权限
 */
class SettingController extends BaseController
{
    public function __construct(private readonly SettingsService $service) {}

    public function index(Request $request): JsonResponse
    {
        $this->authorize('viewAny', Setting::class);

        $group = $request->input('group', 'default');
        $settings = Setting::where('group', $group)->get();
        return ApiResponse::success($settings);
    }

    public function store(Request $request): JsonResponse
    {
        $this->authorize('create', Setting::class);

        $data = $request->validate([
            'group' => 'nullable|string|max:50',
            'key' => 'required|string|max:100',
            'value' => 'required',
            'type' => 'nullable|string|in:string,int,bool,json,float,encrypted',
            'description' => 'nullable|string|max:255',
        ]);
        $setting = $this->service->set(
            $data['key'], $data['value'], $data['type'] ?? 'string',
            $data['group'] ?? 'default', $data['description'] ?? null,
        );
        return ApiResponse::created($setting);
    }

    public function show(string $group, string $key): JsonResponse
    {
        $this->authorize('view', Setting::class);

        $value = $this->service->get($key, null, $group);
        return ApiResponse::success(['group' => $group, 'key' => $key, 'value' => $value]);
    }

    public function update(Request $request, string $group, string $key): JsonResponse
    {
        $this->authorize('update', Setting::class);

        $data = $request->validate([
            'value' => 'required',
            'type' => 'nullable|string|in:string,int,bool,json,float,encrypted',
        ]);
        $setting = $this->service->set($key, $data['value'], $data['type'] ?? 'string', $group);
        return ApiResponse::success($setting);
    }

    public function destroy(string $group, string $key): JsonResponse
    {
        $this->authorize('delete', Setting::class);

        $this->service->delete($key, $group);
        return ApiResponse::success(null, '删除成功');
    }
}