<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DefStudio\Telegraph\Models\TelegraphBot;
use DefStudio\Telegraph\Facades\Telegraph;

class SetupTelegramBot extends Command
{
    protected $signature = 'telegram:setup';
    protected $description = 'Setup Telegram bot for Telegraph';

    public function handle()
    {
        $this->info('Setting up Telegram bot...');

        $token = config('telegraph.bots.default.token');
        if (!$token) {
            $this->error('TELEGRAPH_TOKEN not configured in .env');
            return 1;
        }

        // Create or update bot
        $bot = TelegraphBot::updateOrCreate(
            ['token' => $token],
            ['name' => 'HajiBot']
        );

        $this->info("Bot created/updated: {$bot->name} (ID: {$bot->id})");

        // Test bot connection
        try {
            $response = Telegraph::bot($bot)->botInfo()->send();
            $botData = $response->json();
            $this->info("Bot info: {$botData['result']['first_name']} (@{$botData['result']['username']})");
        } catch (\Throwable $e) {
            $this->error("Failed to get bot info: {$e->getMessage()}");
            return 1;
        }

        // Set webhook
        try {
            $response = $bot->registerWebhook()->send();

            if ($response->successful()) {
                $webhookUrl = config('telegraph.bots.default.webhook');
                $this->info("Webhook set successfully: {$webhookUrl}");
            } else {
                $this->error("Failed to set webhook: {$response->body()}");
                return 1;
            }
        } catch (\Throwable $e) {
            $this->error("Failed to set webhook: {$e->getMessage()}");
            return 1;
        }

        $this->info('Telegram bot setup completed successfully!');
        return 0;
    }
}
