<?php

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

use App\Support\ApiResponse;
use App\Models\SettlementBatch;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Support\SettlementBatchFinancialSummary;

/**
 * GET /api/v1/admin/settlement-batches/{batch} — 单批次摘要。
 */
final class AdminSettlementBatchShowController extends Controller
{
    public function __invoke(SettlementBatch $batch): JsonResponse
    {
        $batch->load(['draw:id,draw_no,business_date,status', 'resultBatch:id,result_version,status']);
        $financial = SettlementBatchFinancialSummary::forBatch($batch);

        return ApiResponse::success([
            'id' => (int) $batch->id,
            'draw_id' => (int) $batch->draw_id,
            'draw_no' => $batch->draw?->draw_no,
            'currency_code' => $financial['currency_code'],
            'draw_status' => $batch->draw?->status,
            'result_batch_id' => (int) $batch->result_batch_id,
            'result_batch_version' => $batch->resultBatch?->result_version,
            'result_batch_status' => $batch->resultBatch?->status,
            'settle_version' => (int) $batch->settle_version,
            'status' => $batch->status,
            'review_status' => $batch->review_status,
            'reviewed_by' => $batch->reviewed_by,
            'reviewed_at' => $batch->reviewed_at?->toIso8601String(),
            'review_remark' => $batch->review_remark,
            'paid_at' => $batch->paid_at?->toIso8601String(),
            'total_ticket_count' => (int) $batch->total_ticket_count,
            'total_win_count' => (int) $batch->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) $batch->total_payout_amount,
            'total_payout_amount_minor' => (int) $batch->total_payout_amount,
            'total_jackpot_payout_amount' => (int) $batch->total_jackpot_payout_amount,
            'total_jackpot_payout_amount_minor' => (int) $batch->total_jackpot_payout_amount,
            // 历史字段：保留兼容，实际单位为 minor。
            'platform_profit' => $financial['platform_profit'],
            'platform_profit_minor' => $financial['platform_profit_minor'],
            'started_at' => $batch->started_at?->toIso8601String(),
            'finished_at' => $batch->finished_at?->toIso8601String(),
            'created_at' => $batch->created_at?->toIso8601String(),
        ]);
    }
}
