<?php

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

use App\Models\Draw;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Support\CurrencyResolver;
use App\Models\DrawResultBatch;
use App\Support\PaginationTrait;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Lottery\DrawResultBatchStatus;
use App\Services\Draw\DrawResultViewService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

/**
 * `GET /api/v1/draw/results` — 已发布开奖往期（公开；对齐 PRD `/api/v1/results`）。
 */
final class DrawResultsIndexController extends Controller
{
    use PaginationTrait;

    public function __construct(
        private readonly DrawResultViewService $viewer,
    ) {}

    public function __invoke(Request $request): JsonResponse
    {
        $perPage = $this->perPage($request, 'size', 15, 50);
        $page = $this->page($request);
        /** @var string|null $bizDate query `business_date` 或旧的 `date` */
        $bizDate = $request->query('business_date') ?? $request->query('date');

        $query = Draw::query()
            ->whereIn('status', DrawResultViewService::publishedDrawStatuses())
            ->where('current_result_version', '>', 0)
            ->whereNotNull('draw_time')
            ->whereExists(function ($sub): void {
                $sub->selectRaw('1')
                    ->from((new DrawResultBatch)->getTable())
                    ->whereColumn('draw_id', 'draws.id')
                    ->whereColumn('result_version', 'draws.current_result_version')
                    ->where('status', DrawResultBatchStatus::Published->value);
            });

        if (is_string($bizDate) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $bizDate)) {
            $query->whereDate('business_date', $bizDate);
        }

        /** @var LengthAwarePaginator<int, Draw> $paginator */
        $paginator = $query
            ->orderByDesc('draw_time')
            ->paginate(perPage: $perPage, columns: ['*'], pageName: 'page', page: $page);

        $currencyCode = CurrencyResolver::resolve($request, $request->lotteryPlayer());
        $decorated = $this->viewer->decoratePaginator($paginator, $currencyCode);

        return ApiResponse::success([
            'items' => $decorated->items(),
            'total' => $decorated->total(),
            'page' => $decorated->currentPage(),
            'per_page' => $decorated->perPage(),
            'last_page' => $decorated->lastPage(),
        ]);
    }
}
