<?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\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Lottery\ConfigVersionStatus;
use App\Support\AdminConfigPresenter;
use App\Services\Config\OddsStreamService;

/** POST /api/v1/admin/config/odds-versions/{id}/publish */
final class OddsVersionPublishController 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,
            );
        }

        $service->publish($version, $admin, $request);

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