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

/** POST /api/v1/admin/config/play-versions/{id}/publish */
final class PlayConfigVersionPublishController 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 ApiMessage::errorResponse($request, 'config_version_not_draft', ErrorCode::ConfigVersionNotDraft->value, null, 400);
        }

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

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