<?php

/**
 * 文件功能：百家乐开局队列任务
 *
 * 由调度器每 N 分钟触发一次（N 来自 game_configs.params.interval_minutes），
 * 游戏开启时创建新局次，广播开局事件，并在押注截止时间到期后自动调度结算任务。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Jobs;

use App\Events\BaccaratRoundOpened;
use App\Events\MessageSent;
use App\Models\BaccaratRound;
use App\Models\GameConfig;
use App\Services\ChatStateService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class OpenBaccaratRoundJob implements ShouldQueue
{
    use Queueable;

    /**
     * 最大重试次数。
     */
    public int $tries = 1;

    /**
     * 执行开局逻辑。
     */
    public function handle(ChatStateService $chatState): void
    {
        // 检查游戏是否开启
        if (! GameConfig::isEnabled('baccarat')) {
            return;
        }

        $config = GameConfig::forGame('baccarat')?->params ?? [];
        $betSeconds = (int) ($config['bet_window_seconds'] ?? 60);

        // 防止重复开局（如果上一局还在押注中则跳过）
        if (BaccaratRound::currentRound()) {
            return;
        }

        $now = now();
        $closesAt = $now->copy()->addSeconds($betSeconds);

        // 创建新局次
        $round = BaccaratRound::create([
            'status' => 'betting',
            'bet_opens_at' => $now,
            'bet_closes_at' => $closesAt,
        ]);

        // 广播开局事件
        broadcast(new BaccaratRoundOpened($round));

        // 公屏系统公告
        $minBet = number_format($config['min_bet'] ?? 100);
        $maxBet = number_format($config['max_bet'] ?? 50000);

        $bigRate = (int) ($config['big_rate'] ?? 1);
        $tripleRate = (int) ($config['triple_rate'] ?? 24);
        $killPoints = $config['kill_points'] ?? [3, 18];
        if (! is_array($killPoints)) {
            $killPoints = explode(',', (string) $killPoints);
        }
        $killText = implode('或', array_map('intval', $killPoints));

        $quickOpenButton = '<button type="button" '
            .'onclick="event.preventDefault(); Alpine.$data(document.getElementById(\'baccarat-panel\')).openFromHall();" '
            .'style="margin-left:8px; padding:2px 8px; border:1px solid #7c3aed; border-radius:999px; background:#fff; color:#7c3aed; font-size:12px; font-weight:bold; cursor:pointer;">'
            .'快速参与</button>';
        $content = "🎲 【百家乐】第 #{$round->id} 局开始！下注时间 {$betSeconds} 秒，押注范围 {$minBet}~{$maxBet} 金币。赔率：🔵大/🟡小 1:{$bigRate} · 💥豹子 1:{$tripleRate}（☠️ {$killText} 点庄家收割）".$quickOpenButton;
        $msg = [
            'id' => $chatState->nextMessageId(1),
            'room_id' => 1,
            'from_user' => '系统传音',
            'to_user' => '大家',
            'content' => $content,
            'is_secret' => false,
            'font_color' => '#8b5cf6',
            'action' => '大声宣告',
            'sent_at' => $now->toDateTimeString(),
        ];
        $chatState->pushMessage(1, $msg);
        broadcast(new MessageSent(1, $msg));
        SaveMessageJob::dispatch($msg);

        // 如果允许 AI 参与，延迟一定时间派发 AI 下注任务
        $baccaratEnabled = \App\Models\Sysparam::getValue('chatbot_baccarat_enabled', '0') === '1';
        if (\App\Models\Sysparam::getValue('chatbot_enabled', '0') === '1' && $baccaratEnabled) {
            $aiDelay = rand(10, min(40, max(10, $betSeconds - 5))); // 随机在 10 ~ (倒数前5秒) 之间下注
            \App\Jobs\AiBaccaratBetJob::dispatch($round)->delay(now()->addSeconds($aiDelay));
        }

        // 在下注截止时安排结算任务
        CloseBaccaratRoundJob::dispatch($round)->delay($closesAt);
    }
}
