<?php

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

use App\Models\AdminUser;
use App\Lottery\ErrorCode;
use App\Support\ApiMessage;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Models\PlayConfigVersion;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Lottery\ConfigVersionStatus;
use App\Support\AdminConfigPresenter;
use App\Services\Config\PlayConfigStreamService;

/** PUT /api/v1/admin/config/play-versions/{id}/items */
final class PlayConfigItemsReplaceController extends Controller
{
    public function __invoke(Request $request, int $id, PlayConfigStreamService $service): JsonResponse
    {
        /** @var AdminUser $admin */
        $admin = $request->lotteryAdmin();

        /** @var PlayConfigVersion $version */
        $version = PlayConfigVersion::query()->whereKey($id)->firstOrFail();

        if ($version->status !== ConfigVersionStatus::Draft->value) {
            return ApiResponse::error(
                ApiMessage::get($request, 'config_version_not_draft'),
                ErrorCode::ConfigVersionNotDraft->value,
                null,
                400,
            );
        }

        $data = $request->validate([
            'items' => ['required', 'array', 'min:1'],
            'items.*.play_code' => ['required', 'string', 'max:32', Rule::exists('play_types', 'play_code')],
            'items.*.category' => ['required', 'string', 'max:16'],
            'items.*.dimension' => ['nullable', 'integer', 'min:0', 'max:255'],
            'items.*.bet_mode' => ['nullable', 'string', 'max:32'],
            'items.*.display_name' => ['required', 'string', 'max:64'],
            'items.*.is_enabled' => ['sometimes', 'boolean'],
            'items.*.min_bet_amount' => ['required', 'integer', 'min:0'],
            'items.*.max_bet_amount' => ['required', 'integer', 'min:0'],
            'items.*.display_order' => ['sometimes', 'integer'],
            'items.*.supports_multi_number' => ['sometimes', 'boolean'],
            'items.*.reserved_rule_json' => ['sometimes', 'nullable', 'array'],
            'items.*.rule_text_zh' => ['sometimes', 'nullable', 'string'],
            'items.*.rule_text_en' => ['sometimes', 'nullable', 'string'],
            'items.*.rule_text_ne' => ['sometimes', 'nullable', 'string'],
            'items.*.extra_config_json' => ['sometimes', 'nullable', 'array'],
        ]);

        $service->replaceItems($version, $data['items'], $admin);

        return ApiResponse::success(
            AdminConfigPresenter::playConfigVersionDetail($version->fresh()->load('items')),
        );
    }
}
