<?php

namespace App\Http\Controllers\Api\V1\Setting;

use App\Http\Controllers\Controller;
use App\Models\LotterySetting;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 玩家端/公开：读取 KV 配置（公开访问；仅允许白名单分组）。
 */
final class SettingIndexController extends Controller
{
    /** @var list<string> */
    private const PUBLIC_GROUPS = [
        'frontend',
    ];

    public function __invoke(Request $request): JsonResponse
    {
        $group = $request->query('group');

        if (! is_string($group) || $group === '' || ! in_array($group, self::PUBLIC_GROUPS, true)) {
            return ApiMessage::errorResponse(
                $request,
                'invalid_settings_group',
                ErrorCode::ClientHttpError->value,
                ['allowed_groups' => self::PUBLIC_GROUPS],
                400,
            );
        }

        $items = LotterySetting::query()
            ->where('group_name', $group)
            ->orderBy('setting_key')
            ->get()
            ->map(fn (LotterySetting $s): array => [
                'key' => $s->setting_key,
                'value' => $s->value_json,
                'group' => $s->group_name,
                'description' => $s->description_zh,
            ]);

        return ApiResponse::success(['items' => $items]);
    }
}
