<?php

namespace App\Support;

use App\Models\SettlementBatch;

final class SettlementBatchFinancialSummary
{
    /**
     * 所有金额字段均为最小货币单位（minor）。
     *
     * @return array{
     *   total_bet_amount: int,
     *   total_actual_deduct: int,
     *   platform_profit: int,
     *   total_bet_amount_minor: int,
     *   total_actual_deduct_minor: int,
     *   platform_profit_minor: int,
     *   currency_code: ?string
     * }
     */
    public static function forBatch(SettlementBatch $batch): array
    {
        $totals = $batch->details()
            ->join('ticket_items', 'ticket_items.id', '=', 'ticket_settlement_details.ticket_item_id')
            ->join('ticket_orders', 'ticket_orders.id', '=', 'ticket_items.order_id')
            ->selectRaw('COALESCE(SUM(ticket_items.total_bet_amount), 0) as total_bet_amount')
            ->selectRaw('COALESCE(SUM(ticket_items.actual_deduct_amount), 0) as total_actual_deduct')
            ->selectRaw('MIN(ticket_orders.currency_code) as currency_code')
            ->first();

        $totalBet = (int) ($totals?->total_bet_amount ?? 0);
        $totalActualDeduct = (int) ($totals?->total_actual_deduct ?? 0);
        $totalPayout = (int) $batch->total_payout_amount;

        return [
            'total_bet_amount' => $totalBet,
            'total_actual_deduct' => $totalActualDeduct,
            'platform_profit' => $totalActualDeduct - $totalPayout,
            // 显式别名：避免调用方误解为主货币单位。
            'total_bet_amount_minor' => $totalBet,
            'total_actual_deduct_minor' => $totalActualDeduct,
            'platform_profit_minor' => $totalActualDeduct - $totalPayout,
            'currency_code' => is_string($totals?->currency_code) && $totals->currency_code !== ''
                ? $totals->currency_code
                : null,
        ];
    }
}
