<?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 Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Settlement\SettlementOrchestrator;

/**
 * POST /api/v1/admin/draws/{draw}/settlement/run — 对 `settling` 期号执行结算（可关自动结算时手工触发）。
 */
final class DrawSettlementRunController extends Controller
{
    public function __construct(
        private readonly SettlementOrchestrator $orchestrator,
    ) {}

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

        $ran = $this->orchestrator->trySettleDraw($draw);

        $draw->refresh();

        if (! $ran) {
            return ApiResponse::error(
                trans('admin.settlement_run_skipped', [], $request->lotteryLocale()),
                ErrorCode::ClientHttpError->value,
                [
                    'draw_no' => $draw->draw_no,
                    'status' => $draw->status,
                    'settle_version' => (int) $draw->settle_version,
                ],
                409,
            );
        }

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