<?php

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

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

/**
 * GET /api/v1/admin/settlement-batches — 结算批次分页列表。
 */
final class AdminSettlementBatchIndexController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $admin = $request->lotteryAdmin();
        abort_if($admin === null, 401);

        $p = AdminApiList::readPaging($request);
        $drawNo = trim((string) $request->query('draw_no', ''));
        $status = trim((string) $request->query('status', ''));
        $scope = AdminScopePolicy::resolveContext($request, $admin);

        $q = SettlementBatch::query()
            ->with(['draw:id,draw_no'])
            ->orderByDesc('id');

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

        if ($drawNo !== '') {
            $q->whereHas('draw', fn ($d) => $d->where('draw_no', 'like', '%'.$drawNo.'%'));
        }

        if ($status !== '') {
            $q->where('status', $status);
        }

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

        return AdminApiList::json($paginator, fn (SettlementBatch $b) => $this->row($b));
    }

    /** @return array<string, mixed> */
    private function row(SettlementBatch $b): array
    {
        $financial = SettlementBatchFinancialSummary::forBatch($b);

        return [
            'id' => (int) $b->id,
            'draw_id' => (int) $b->draw_id,
            'draw_no' => $b->draw?->draw_no,
            'currency_code' => $financial['currency_code'],
            'result_batch_id' => (int) $b->result_batch_id,
            'settle_version' => (int) $b->settle_version,
            'status' => $b->status,
            'review_status' => $b->review_status,
            'reviewed_at' => $b->reviewed_at?->toIso8601String(),
            'paid_at' => $b->paid_at?->toIso8601String(),
            'total_ticket_count' => (int) $b->total_ticket_count,
            'total_win_count' => (int) $b->total_win_count,
            // 历史字段：保留兼容，实际单位为 minor。
            'total_bet_amount' => $financial['total_bet_amount'],
            'total_bet_amount_minor' => $financial['total_bet_amount_minor'],
            // 历史字段：保留兼容，实际单位为 minor。
            'total_actual_deduct' => $financial['total_actual_deduct'],
            'total_actual_deduct_minor' => $financial['total_actual_deduct_minor'],
            // settlement_batches 表内派彩金额一直按 minor 存储。
            'total_payout_amount' => (int) $b->total_payout_amount,
            'total_payout_amount_minor' => (int) $b->total_payout_amount,
            'total_jackpot_payout_amount' => (int) $b->total_jackpot_payout_amount,
            'total_jackpot_payout_amount_minor' => (int) $b->total_jackpot_payout_amount,
            // 历史字段：保留兼容，实际单位为 minor。
            'platform_profit' => $financial['platform_profit'],
            'platform_profit_minor' => $financial['platform_profit_minor'],
            'started_at' => $b->started_at?->toIso8601String(),
            'finished_at' => $b->finished_at?->toIso8601String(),
            'created_at' => $b->created_at?->toIso8601String(),
        ];
    }
}
