<?php

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

use App\Models\Draw;
use App\Models\AdminUser;
use App\Lottery\ErrorCode;
use App\Support\ApiResponse;
use App\Support\ApiMessage;
use Illuminate\Http\Request;
use App\Models\DrawResultBatch;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Draw\DrawPublishService;

/**
 * POST /api/v1/admin/draws/{draw}/result-batches/{batch}/publish — 人工审核发布 RNG 批次。
 */
final class DrawResultBatchPublishController extends Controller
{
    public function __construct(
        private readonly DrawPublishService $publishService,
    ) {}

    public function __invoke(Request $request, Draw $draw, DrawResultBatch $batch): JsonResponse
    {
        $admin = $request->user();
        if (! $admin instanceof AdminUser) {
            return ApiResponse::error(
                trans('admin.unauthenticated', [], $request->lotteryLocale()),
                ErrorCode::AdminUnauthenticated->value,
                null,
                401,
            );
        }

        if ((int) $batch->draw_id !== (int) $draw->id) {
            return ApiResponse::error(
                trans('api.not_found', [], $request->lotteryLocale()),
                ErrorCode::NotFound->value,
                null,
                404,
            );
        }

        try {
            $this->publishService->publishManualBatch($batch, $admin);
        } catch (\RuntimeException $e) {
            return ApiMessage::runtimeErrorResponse($request, $e);
        }

        $draw->refresh();

        return ApiResponse::success([
            'draw_no' => $draw->draw_no,
            'status' => $draw->status,
            'result_version' => (int) $draw->current_result_version,
        ]);
    }
}
