<?php

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

use App\Models\Draw;
use App\Support\ApiResponse;
use App\Models\DrawResultBatch;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\AdminDrawApiPresenter;
use App\Support\AdminDrawResponsePolicy;
use App\Lottery\DrawResultBatchStatus;

/**
 * GET /api/v1/admin/draws/{draw}/result-batches — 开奖批次与号码（审核/结果核对）。
 */
final class AdminDrawResultBatchesIndexController extends Controller
{
    public function __invoke(Request $request, Draw $draw): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $manage = AdminDrawResponsePolicy::canManageDrawResults($admin);

        $query = $draw->resultBatches()
            ->with(['items' => function ($q): void {
                $q->orderBy('prize_type')->orderBy('prize_index');
            }])
            ->orderByDesc('result_version');

        if (! $manage) {
            $query->where('status', DrawResultBatchStatus::Published->value);
        }

        $batches = $query->get();

        return ApiResponse::success([
            'draw_id' => (int) $draw->id,
            'draw_no' => $draw->draw_no,
            'draw_status' => $draw->status,
            'capabilities' => AdminDrawResponsePolicy::capabilities($admin),
            'batches' => $batches
                ->map(fn (DrawResultBatch $b): array => AdminDrawApiPresenter::resultBatch($b, $admin))
                ->all(),
        ]);
    }
}
