<?php

namespace App\Services\Jackpot;

use App\Models\Draw;
use App\Models\TicketItem;
use App\Models\JackpotPool;
use App\Models\JackpotContribution;

/**
 * 产品文档 §5.11.1：每笔满足门槛的有效注单按下注额比例蓄水（在下注成功路径调用，非结算）。
 */
final class JackpotContributionService
{
    public function recordFromPlacedTicketItem(TicketItem $item, Draw $draw, string $currencyCode): void
    {
        $currency = strtoupper($currencyCode);
        $pool = JackpotPool::query()
            ->where('currency_code', $currency)
            ->where('status', 1)
            ->lockForUpdate()
            ->first();

        if ($pool === null) {
            return;
        }

        $betAmount = (int) $item->total_bet_amount;

        if ($betAmount < (int) $pool->min_bet_amount) {
            return;
        }

        $rate = (float) $pool->contribution_rate;
        $contrib = (int) floor($betAmount * $rate);
        if ($contrib <= 0) {
            return;
        }

        $existing = JackpotContribution::query()
            ->where('ticket_item_id', $item->id)
            ->first();

        if ($existing !== null) {
            return;
        }

        JackpotContribution::query()->create([
            'jackpot_pool_id' => $pool->id,
            'draw_id' => $draw->id,
            'player_id' => $item->player_id,
            'ticket_item_id' => $item->id,
            'contribution_amount' => $contrib,
            'currency_code' => $currency,
        ]);

        $pool->forceFill([
            'current_amount' => (int) $pool->current_amount + $contrib,
        ])->save();
    }
}
