<?php

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

use App\Models\Draw;
use App\Lottery\ErrorCode;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Support\CurrencyResolver;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Services\Draw\DrawResultViewService;

/**
 * `GET /api/v1/draw/results/{draw_no}` — 单期详情（便于玩家端[< >]切换）。
 */
final class DrawResultShowController extends Controller
{
    public function __construct(
        private readonly DrawResultViewService $viewer,
    ) {}

    public function __invoke(Request $request, string $draw_no): JsonResponse
    {
        $draw_no = trim($draw_no);

        $draw = Draw::query()->where('draw_no', $draw_no)->first();
        if ($draw === null) {
            return ApiResponse::error(
                trans('api.not_found', [], $request->lotteryLocale()),
                ErrorCode::NotFound->value,
                null,
                404,
            );
        }

        if (! in_array($draw->status, DrawResultViewService::publishedDrawStatuses(), true)) {
            return ApiResponse::error(
                trans('api.not_found', [], $request->lotteryLocale()),
                ErrorCode::NotFound->value,
                null,
                404,
            );
        }

        $currencyCode = CurrencyResolver::resolve($request, $request->lotteryPlayer());
        $payload = $this->viewer->summarizeDraw($draw, $currencyCode);
        if ($payload === null) {
            return ApiResponse::error(
                trans('api.not_found', [], $request->lotteryLocale()),
                ErrorCode::NotFound->value,
                null,
                404,
            );
        }

        $payload = [...$payload, ...$this->viewer->neighborsIsoTime($draw)];

        return ApiResponse::success($payload);
    }
}
