<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\Core\AppBootstrapper;
use App\Framework\Notification\Channels\Telegram\TelegramClient;

echo "🔧 Telegram Webhook Setup\n";
echo str_repeat('=', 50) . "\n\n";

// Bootstrap application
$container = (new AppBootstrapper())->boot();
$client = $container->get(TelegramClient::class);

// Configuration
$webhookUrl = 'https://your-domain.com/webhooks/telegram';
$secretToken = bin2hex(random_bytes(16)); // Generate random secret token

echo "📋 Configuration:\n";
echo "   Webhook URL: {$webhookUrl}\n";
echo "   Secret Token: {$secretToken}\n\n";

echo "⚠️  IMPORTANT: Add this to your .env file:\n";
echo "   TELEGRAM_WEBHOOK_SECRET={$secretToken}\n\n";

try {
    // Step 1: Delete existing webhook (if any)
    echo "🗑️  Deleting existing webhook...\n";
    $client->deleteWebhook();
    echo "   ✅ Existing webhook deleted\n\n";

    // Step 2: Set new webhook
    echo "🔗 Setting new webhook...\n";
    $success = $client->setWebhook(
        url: $webhookUrl,
        secretToken: $secretToken,
        allowedUpdates: ['message', 'callback_query', 'edited_message']
    );

    if ($success) {
        echo "   ✅ Webhook configured successfully!\n\n";

        echo "📝 Next steps:\n";
        echo "   1. Add TELEGRAM_WEBHOOK_SECRET to your .env file\n";
        echo "   2. Make sure your webhook URL is publicly accessible via HTTPS\n";
        echo "   3. Test by sending a message to your bot or clicking an inline keyboard button\n\n";

        echo "🧪 To test callback buttons, run:\n";
        echo "   php tests/debug/test-telegram-webhook-buttons.php\n\n";
    } else {
        echo "   ❌ Failed to set webhook\n";
        exit(1);
    }

} catch (\Exception $e) {
    echo "❌ Error: {$e->getMessage()}\n";
    echo "\n📋 Details:\n";
    echo $e->getTraceAsString() . "\n";
    exit(1);
}

echo "✨ Setup complete!\n";
