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

/** POST /api/v1/admin/config/risk-cap-versions/{id}/publish */
final class RiskCapVersionPublishController extends Controller
{
    public function __invoke(Request $request, int $id, RiskCapStreamService $service): JsonResponse
    {
        /** @var AdminUser $admin */
        $admin = $request->lotteryAdmin();

        /** @var RiskCapVersion $version */
        $version = RiskCapVersion::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::riskCapVersionDetail($version->fresh()->load('items')),
        );
    }
}
