<?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 SendTelegramMessageJob implements ShouldQueue
{
    use Dispatchable, HandlesTelegramJobFailure, InteractsWithQueue, Queueable, SerializesModels;

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

    public $chatId;
    public $text;
    public $buttons;
    public $image;
    public $isTop;

    /**
     * @param string $chatId
     * @param string $text
     * @param array $buttons
     * @param string|null $image
     */
    public function __construct($chatId, $text, $buttons = [], $image = null ,$isTop = false)
    {
        $this->chatId = $chatId;
        $this->text = $text;
        $this->buttons = $buttons;
        $this->image = $image;
        $this->isTop = $isTop;
    }

    public function handle()
    {
        try {
            BaseService::sendMessage($this->chatId ,$this->text, $this->buttons, $this->image);
            Log::channel('issue')->info('Telegram私聊消息发送成功', [
                'attempt' => $this->attempts(),
                'chat_id' => $this->chatId,
                'text_length' => strlen((string)$this->text),
                'has_image' => !empty($this->image),
            ]);
        } catch (\Throwable $exception) {
            $this->handleTelegramJobFailure($exception, 'Telegram私聊消息发送失败', [
                'chat_id' => $this->chatId,
                'text_length' => strlen((string)$this->text),
                'has_image' => !empty($this->image),
            ], false);
        }
    }
}
