<?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;

/**
 * head / tail / odd / even / digit_big / digit_small：展开组合中若有与**头奖 4D** 完全一致则中奖（赔率档 first）。
 */
final class FirstPrizeComboSettlementMatcher implements SettlementPlayMatcher
{
    public function __construct(
        private readonly OddsSnapshotReader $odds,
    ) {}

    public function match(TicketItem $item, PublishedDrawResultBoard $board, Collection $combinations): array
    {
        $first = $board->firstPrizeNumber4d();
        if ($first === '') {
            return ['win_amount' => 0, 'matched_prize_tier' => null, 'match_detail' => ['reason' => 'no_first']];
        }

        $snapshot = is_array($item->odds_snapshot_json) ? $item->odds_snapshot_json : null;
        $oddsVal = $this->odds->oddsValueForScope($snapshot, 'first');
        $lines = [];
        $total = 0;

        foreach ($combinations as $c) {
            /** @var TicketCombination $c */
            if ((string) $c->number_4d !== $first) {
                continue;
            }
            $bet = (int) $c->bet_amount;
            $payout = (int) floor($bet * ($oddsVal / 10_000));
            $total += $payout;
            $lines[] = ['number_4d' => $c->number_4d, 'bet_amount' => $bet, 'payout' => $payout];
        }

        return [
            'win_amount' => $total,
            'matched_prize_tier' => $total > 0 ? 'first' : null,
            'match_detail' => ['lines' => $lines, 'first_prize' => $first],
        ];
    }
}
