<?php

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

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

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

        /** @var OddsVersion $version */
        $version = OddsVersion::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.*.prize_scope' => ['required', 'string', 'max:32'],
            'items.*.odds_value' => ['required', 'integer', 'min:0'],
            'items.*.rebate_rate' => ['sometimes', 'numeric', 'between:0,1'],
            'items.*.commission_rate' => ['sometimes', 'numeric', 'between:0,1'],
            'items.*.currency_code' => ['required', 'string', 'max:16', Rule::exists('currencies', 'code')],
            'items.*.extra_config_json' => ['sometimes', 'nullable', 'array'],
        ]);

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

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