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

/** pos_4a / pos_4b / pos_4c：与对应档完整 4D 一致。 */
final class Pos4ExactTierSettlementMatcher implements SettlementPlayMatcher
{
    /** @var array<string, string> */
    private const PLAY_TO_TIER = [
        'pos_4a' => 'first',
        'pos_4b' => 'second',
        'pos_4c' => 'third',
    ];

    public function __construct(
        private readonly OddsSnapshotReader $odds,
    ) {}

    public function match(TicketItem $item, PublishedDrawResultBoard $board, Collection $combinations): array
    {
        $tier = self::PLAY_TO_TIER[$item->play_code] ?? 'first';
        $row = $board->row($tier, 0);
        if ($row === null) {
            return ['win_amount' => 0, 'matched_prize_tier' => null, 'match_detail' => ['reason' => 'no_row']];
        }
        $target = (string) $row->number_4d;
        $snapshot = is_array($item->odds_snapshot_json) ? $item->odds_snapshot_json : null;
        $oddsVal = $this->odds->oddsValueForScope($snapshot, $tier);
        $lines = [];
        $total = 0;

        foreach ($combinations as $c) {
            /** @var TicketCombination $c */
            if ((string) $c->number_4d !== $target) {
                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 ? $tier : null,
            'match_detail' => ['lines' => $lines, 'target' => $target],
        ];
    }
}
