<?php

namespace App\Jobs\Concerns;

use Illuminate\Support\Facades\Log;
use RuntimeException;
use Throwable;

trait HandlesTelegramJobFailure
{
    private function handleTelegramJobFailure(Throwable $exception, string $message, array $context = [], bool $shouldThrow = true): void
    {
        $safeMessage = $this->sanitizeTelegramError($exception->getMessage());
        $willRetry = $shouldThrow && $this->isRetryableTelegramJobError($safeMessage);
        $context = array_merge($context, [
            'attempt' => method_exists($this, 'attempts') ? $this->attempts() : 1,
            'error' => $safeMessage,
            'exception' => get_class($exception),
        ]);

        Log::channel('issue')->warning($message, $context + [
            'will_retry' => $willRetry,
        ]);

        if ($willRetry) {
            throw new RuntimeException($safeMessage);
        }
    }

    private function sanitizeTelegramError(string $message): string
    {
        return preg_replace('/bot\d+:[A-Za-z0-9_-]+/', 'bot[redacted]', $message);
    }

    private function isRetryableTelegramJobError(string $message): bool
    {
        return str_contains($message, 'Too Many Requests')
            || str_contains($message, 'retry after')
            || str_contains($message, 'cURL error 7')
            || str_contains($message, 'cURL error 28')
            || str_contains($message, 'Failed to connect')
            || str_contains($message, 'Connection timed out')
            || str_contains($message, 'Operation timed out');
    }
}
