<?php

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

use App\Models\PlayType;
use App\Models\AdminUser;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminConfigPresenter;
use App\Services\Config\PlayConfigStreamService;

/**
 * PATCH /api/v1/admin/play-types/{play_code}
 *
 * is_enabled 写入当前生效玩法配置并即时推送大厅；其余字段仅更新主目录 play_types。
 */
final class PlayTypePatchController extends Controller
{
    public function __construct(
        private readonly PlayConfigStreamService $playConfig,
    ) {}

    public function __invoke(Request $request, string $play_code): JsonResponse
    {
        /** @var AdminUser $admin */
        $admin = $request->lotteryAdmin();

        /** @var PlayType $type */
        $type = PlayType::query()->where('play_code', $play_code)->firstOrFail();

        $data = $request->validate([
            'is_enabled' => ['sometimes', 'boolean'],
            'sort_order' => ['sometimes', 'integer'],
            'display_name' => ['sometimes', 'nullable', 'string', 'max:64'],
            'supports_multi_number' => ['sometimes', 'boolean'],
            'reserved_rule_json' => ['sometimes', 'nullable', 'array'],
        ]);

        if (array_key_exists('is_enabled', $data)) {
            $this->playConfig->patchActivePlayToggle($admin, $play_code, (bool) $data['is_enabled'], $request);
            unset($data['is_enabled']);
        }

        if ($data !== []) {
            $type->fill($data);
            $type->save();
        }

        return ApiResponse::success(AdminConfigPresenter::playType($type->fresh()));
    }
}
