<?php
declare(strict_types=1);

namespace app\process;

use app\dice\logic\reward_config_record\WeightTestRunner;
use app\dice\model\reward_config_record\DiceRewardConfigRecord;
use Workerman\Timer;
use Workerman\Worker;

/**
 * 一键测试权重定时任务进程：每隔一定时间检查 status=0 的测试记录并执行一条，不占用 HTTP  worker 资源
 */
class WeightTestProcess
{
    /** 轮询间隔（秒） */
    private const INTERVAL = 15;

    public function onWorkerStart(Worker $worker): void
    {
        Timer::add(self::INTERVAL, function () {
            $this->runOnePending();
        });
    }

    /**
     * 执行一条待完成的测试记录（status=0）
     * 先原子更新为 STATUS_EXECUTING，避免定时器 15 秒重入时同一条记录被重复执行（导致顺/逆时针各跑两倍次数）
     */
    private function runOnePending(): void
    {
        $record = DiceRewardConfigRecord::where('status', DiceRewardConfigRecord::STATUS_RUNNING)
            ->order('id')
            ->find();
        if (!$record) {
            return;
        }
        $recordId = (int) $record->id;
        $affected = DiceRewardConfigRecord::where('id', $recordId)
            ->where('status', DiceRewardConfigRecord::STATUS_RUNNING)
            ->update(['status' => DiceRewardConfigRecord::STATUS_EXECUTING]);
        if ($affected !== 1) {
            return;
        }
        try {
            (new WeightTestRunner())->run($recordId);
        } catch (\Throwable $e) {
            // WeightTestRunner 内部会更新 status=-1 和 remark
        }
    }
}
