<?php

/**
 * 文件功能：异步发送微信机器人消息任务
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Jobs;

use App\Models\SysParam;
use App\Services\WechatBot\WechatBotApiService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SendWechatBotMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var string 目标 wxid 或 群组 ID (@chatroom)
     */
    protected string $target;

    /**
     * @var string 要发送的消息内容
     */
    protected string $message;

    /**
     * 队列任务构造函数
     *
     * @param  string  $target  目标用户或群聊
     * @param  string  $message  正文内容
     */
    public function __construct(string $target, string $message)
    {
        $this->target = $target;
        $this->message = $message;
    }

    /**
     * 执行任务
     */
    public function handle(WechatBotApiService $apiService): void
    {
        if (empty($this->target)) {
            Log::warning('WechatBot: Target is empty, skipping message dispatch.');

            return;
        }

        // 所有的触发开关判断（如百家乐、管理员上线等）已经提前在 WechatNotificationService 中拦截判断过了。
        // 所以能进入到这个任务的消息，都是明确需要发送的。

        try {
            $apiService->sendTextMessage($this->target, $this->message);
        } catch (\Exception $e) {
            Log::error('WechatBot: Failed to send message in queue', [
                'target' => $this->target,
                'message' => $this->message,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
