<?php

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

use App\Models\Draw;
use App\Models\RiskPool;
use App\Lottery\ErrorCode;
use App\Models\TicketOrder;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use App\Support\AdminApiList;
use App\Models\RiskPoolLockLog;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

/**
 * GET /api/v1/admin/draws/{draw}/risk-pools/{number_4d} — 单号码风险池详情 + 占用流水。
 */
final class AdminRiskPoolShowController extends Controller
{
    public function __invoke(Request $request, Draw $draw, string $number_4d): JsonResponse
    {
        if (preg_match('/^[0-9]{4}$/', $number_4d) !== 1) {
            return ApiResponse::error(
                trans('api.validation_failed', [], $request->lotteryLocale()),
                ErrorCode::ValidationFailed->value,
                null,
                422,
            );
        }

        $pool = RiskPool::query()
            ->where('draw_id', $draw->id)
            ->where('normalized_number', $number_4d)
            ->first();

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

        $p = AdminApiList::readPaging($request, 20, AdminApiList::MAX_PER_PAGE);

        /** @var LengthAwarePaginator $paginator */
        $paginator = RiskPoolLockLog::query()
            ->where('draw_id', $draw->id)
            ->where('normalized_number', $number_4d)
            ->with(['ticketItem:id,ticket_no,play_code,player_id'])
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->paginate($p['perPage'], ['*'], 'page', $p['page']);

        $cap = (int) $pool->total_cap_amount;
        $locked = (int) $pool->locked_amount;
        $currencyCode = (string) (TicketOrder::query()
            ->where('draw_id', $draw->id)
            ->value('currency_code') ?? '');

        return ApiResponse::success([
            'draw_id' => (int) $draw->id,
            'draw_no' => $draw->draw_no,
            'currency_code' => $currencyCode !== '' ? $currencyCode : null,
            'pool' => [
                'normalized_number' => $pool->normalized_number,
                'total_cap_amount' => $cap,
                'locked_amount' => $locked,
                'remaining_amount' => (int) $pool->remaining_amount,
                'sold_out_status' => (int) $pool->sold_out_status,
                'is_sold_out' => (int) $pool->sold_out_status === 1,
                'usage_ratio' => $cap > 0 ? round($locked / $cap, 6) : null,
                'version' => (int) $pool->version,
            ],
            'logs' => AdminApiList::payload($paginator, fn (RiskPoolLockLog $log) => $this->logRow($log)),
        ]);
    }

    /** @return array<string, mixed> */
    private function logRow(RiskPoolLockLog $log): array
    {
        return [
            'id' => (int) $log->id,
            'action_type' => $log->action_type,
            'amount' => (int) $log->amount,
            'source_reason' => $log->source_reason,
            'ticket_item_id' => $log->ticket_item_id,
            'ticket_no' => $log->ticketItem?->ticket_no,
            'play_code' => $log->ticketItem?->play_code,
            'player_id' => $log->ticketItem?->player_id,
            'created_at' => $log->created_at?->toIso8601String(),
        ];
    }
}
