<?php

namespace App\Services\Settlement\Matchers;

use App\Models\TicketItem;
use App\Models\TicketCombination;
use Illuminate\Support\Collection;
use App\Services\Settlement\OddsSnapshotReader;
use App\Services\Settlement\PublishedDrawResultBoard;
use App\Services\Settlement\Contracts\SettlementPlayMatcher;

/**
 * Big / 包号展开类：命中 23 档中**最优档**计奖（产品文档 Big / iBox / mBox / Box）。
 */
final class BigSpreadSettlementMatcher implements SettlementPlayMatcher
{
    public function __construct(
        private readonly OddsSnapshotReader $odds,
    ) {}

    public function match(TicketItem $item, PublishedDrawResultBoard $board, Collection $combinations): array
    {
        $snapshot = is_array($item->odds_snapshot_json) ? $item->odds_snapshot_json : null;
        $lines = [];
        $total = 0;
        $bestTier = null;
        $bestRank = 99;

        foreach ($combinations as $c) {
            /** @var TicketCombination $c */
            $hit = $board->bestTierForNumber((string) $c->number_4d);
            if ($hit === null) {
                continue;
            }
            $tier = $hit['tier'];
            $oddsVal = $this->odds->oddsValueForScope($snapshot, $tier);
            $bet = (int) $c->bet_amount;
            $payout = (int) floor($bet * ($oddsVal / 10_000));
            $total += $payout;
            $lines[] = [
                'number_4d' => $c->number_4d,
                'matched_tier' => $tier,
                'bet_amount' => $bet,
                'odds_value' => $oddsVal,
                'payout' => $payout,
            ];
            if ($hit['rank'] < $bestRank) {
                $bestRank = $hit['rank'];
                $bestTier = $tier;
            }
        }

        return [
            'win_amount' => $total,
            'matched_prize_tier' => $bestTier,
            'match_detail' => ['lines' => $lines],
        ];
    }
}
