<?php

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

use Illuminate\Http\Request;
use App\Support\AdminApiList;
use App\Support\AdminScopePolicy;
use App\Support\AgentNodeApiPresenter;
use App\Models\SettlementBatch;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Models\TicketSettlementDetail;

/**
 * GET /api/v1/admin/settlement-batches/{batch}/details — 该批次下注单结算明细分页。
 */
final class AdminSettlementBatchDetailsController extends Controller
{
    public function __invoke(Request $request, SettlementBatch $batch): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $p = AdminApiList::readPaging($request);
        $scope = AdminScopePolicy::resolveContext($request, $admin);

        $detailQuery = TicketSettlementDetail::query()
            ->where('settlement_batch_id', $batch->id)
            ->with([
                'ticketItem:id,ticket_no,play_code,player_id',
                'ticketItem.player:id,site_code,username,nickname,site_player_id,agent_node_id',
                'ticketItem.player.agentNode:id,code,name',
                'ticketItem.order:id,currency_code',
            ]);

        if (! $scope->isSuperAdmin() || $scope->effectiveRequestedAgentNodeId() !== null) {
            $detailQuery->whereHas('ticketItem.player', function ($playerQuery) use ($scope): void {
                AdminScopePolicy::applyPlayerFilters($playerQuery, $scope);
            });
        }

        $paginator = $detailQuery
            ->orderBy('id')
            ->paginate($p['perPage'], ['*'], 'page', $p['page']);

        return AdminApiList::jsonWith($paginator, function ($row) {
            /** @var TicketSettlementDetail $row */
            $item = $row->ticketItem;
            $player = $item?->player;
            $order = $item?->order;

            return [
                'id' => (int) $row->id,
                'ticket_item_id' => (int) $row->ticket_item_id,
                ...AgentNodeApiPresenter::embed($player?->agentNode),
                'ticket_no' => $item?->ticket_no,
                'play_code' => $item?->play_code,
                'currency_code' => $order?->currency_code,
                'player_id' => $item?->player_id,
                'site_code' => $player?->site_code,
                'site_player_id' => $player?->site_player_id,
                'username' => $player?->username,
                'nickname' => $player?->nickname,
                'matched_prize_tier' => $row->matched_prize_tier,
                'win_amount' => (int) $row->win_amount,
                'jackpot_allocation_amount' => (int) $row->jackpot_allocation_amount,
                'match_detail_json' => $row->match_detail_json,
                'created_at' => $row->created_at?->toIso8601String(),
            ];
        }, ['batch_id' => (int) $batch->id]);
    }
}
