<?php


namespace App\Jobs;

use App\Jobs\Concerns\HandlesTelegramJobFailure;
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;
use App\Services\BaseService;

class SendTelegramGroupMessageJob implements ShouldQueue
{
    use Dispatchable, HandlesTelegramJobFailure, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 1;
    public $timeout = 85;

    public $chatId;
    public $text;
    public $buttons;
    public $image;
    public $isTop;
    public $separator;
    public $meta = [];

    /**
     * @param string $chatId
     * @param string $text
     * @param array $buttons
     * @param string|null $image
     * @param string $separator 分隔符
     * @param array $meta 日志上下文
     */
    public function __construct($text, $buttons = [], $image = null, $isTop = false, $separator = "\n", $meta = [])
    {
        $this->text = $text;
        $this->buttons = $buttons;
        $this->image = $image;
        $this->isTop = $isTop;
        $this->separator = $separator;
        $this->meta = $meta;
    }

    public function handle()
    {
        $meta = is_array($this->meta) ? $this->meta : [];
        try {
            BaseService::bettingGroupNotice($this->text, $this->buttons, $this->image, $this->isTop, $this->separator);
            Log::channel('issue')->info('Telegram群消息发送成功', array_merge([
                'attempt' => $this->attempts(),
                'text_length' => strlen((string)$this->text),
                'has_image' => !empty($this->image),
                'is_top' => $this->isTop,
                'message_type' => $meta['message_type'] ?? 'unknown',
            ], $meta));
        } catch (\Throwable $exception) {
            $this->handleTelegramJobFailure($exception, 'Telegram群消息发送失败', array_merge([
                'text_length' => strlen((string)$this->text),
                'has_image' => !empty($this->image),
                'is_top' => $this->isTop,
                'message_type' => $meta['message_type'] ?? 'unknown',
            ], $meta), false);
        }
    }
}
