<?php

/**
 * 文件功能：双色球开新期队列任务
 *
 * 在系统初始化时或管理员手动触发时使用，
 * 创建第一期并设置好截止/开奖时间。
 * 正常情况下，开奖后由 LotteryService::openNextIssue() 自动创建下一期。
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Jobs;

use App\Models\GameConfig;
use App\Models\LotteryIssue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class OpenLotteryIssueJob implements ShouldQueue
{
    use Queueable;

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

    /**
     * 执行开新期逻辑（仅在无当前期时创建）。
     */
    public function handle(): void
    {
        if (! GameConfig::isEnabled('lottery')) {
            return;
        }

        // 已有进行中的期次则跳过
        if (LotteryIssue::currentIssue()) {
            return;
        }

        $config = GameConfig::forGame('lottery')?->params ?? [];
        $drawHour = (int) ($config['draw_hour'] ?? 20);
        $drawMinute = (int) ($config['draw_minute'] ?? 0);
        $stopMinutes = (int) ($config['stop_sell_minutes'] ?? 2);

        // 今天的开奖时间；若当前时间已过今日开奖时间，则用明天
        $drawAt = now()->setTime($drawHour, $drawMinute, 0);
        if ($drawAt->isPast()) {
            $drawAt->addDay();
        }

        $closeAt = $drawAt->copy()->subMinutes($stopMinutes);

        LotteryIssue::create([
            'issue_no' => LotteryIssue::nextIssueNo(),
            'status' => 'open',
            'pool_amount' => 0,
            'carry_amount' => 0,
            'is_super_issue' => false,
            'no_winner_streak' => 0,
            'sell_closes_at' => $closeAt,
            'draw_at' => $drawAt,
        ]);
    }
}
