<?php

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

use App\Support\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * E2E 辅助：只读探查（用于断言前的"准"快照）。
 *
 * - credit-ledger: 玩家最近 N 条 credit_ledger 流水
 * - wallet-txns:   玩家最近 N 条 wallet_transactions
 * - ticket-items:  玩家最近 N 条 ticket_items
 *
 * 这些是真实表 + 真实 SQL，但只读不写；只用于 e2e 写断言时核对中间态。
 * 严格仅在 LOTTERY_E2E=true 时由 E2EServiceProvider 注册。
 */
final class E2EInspectController extends \App\Http\Controllers\Controller
{
    public function creditLedger(Request $request): JsonResponse
    {
        return $this->tailTable('credit_ledger', $request);
    }

    public function walletTxns(Request $request): JsonResponse
    {
        return $this->tailTable('wallet_txns', $request);
    }

    public function ticketItems(Request $request): JsonResponse
    {
        return $this->tailTable('ticket_items', $request);
    }

    /**
     * @return JsonResponse
     */
    private function tailTable(string $table, Request $request): JsonResponse
    {
        $limit = max(1, min(100, (int) $request->input('limit', 20)));
        $playerId = $request->input('player_id');

        $q = DB::table($table);
        if ($playerId !== null) {
            $pid = (int) $playerId;
            if ($table === 'credit_ledger') {
                $q->where('owner_type', 'player')->where('owner_id', $pid);
            } else {
                $q->where('player_id', $pid);
            }
        }
        $rows = $q->orderByDesc('id')->limit($limit)->get();

        return ApiResponse::success([
            'table' => $table,
            'count' => $rows->count(),
            'rows' => $rows->map(fn ($r) => (array) $r)->values()->all(),
        ]);
    }
}
