<?php

declare(strict_types=1);

namespace App\Scenario;

use App\Util\ParsedCommand;
use Pkirillw\MaxBotApi\Builder\Message as MessageBuilder;
use Pkirillw\MaxBotApi\Scheme\BotPatch;
use Pkirillw\MaxBotApi\Scheme\Enum\Format;
use Pkirillw\MaxBotApi\Scheme\Update\MessageCreatedUpdate;

final class BotInfoScenario extends AbstractScenario
{
    public function handle(MessageCreatedUpdate $update, ParsedCommand $command): void
    {
        if ($command->name === 'bot') {
            $this->showBot($update);
            return;
        }
        if ($command->name === 'bot_patch') {
            $this->patchBot($update, $command);
            return;
        }
    }

    private function showBot(MessageCreatedUpdate $update): void
    {
        $info = $this->api->bots->getBot();
        $commands = [];
        foreach ($info->commands as $c) {
            $commands[] = sprintf('  • /%s — %s', $c->name, $c->description);
        }
        $text = sprintf(
            "*Bot info*\nname: %s\nusername: @%s\nuserId: %d\ndescription: %s\ncommands:\n%s",
            $info->name,
            $info->username ?? '—',
            $info->userId,
            $info->description ?? '—',
            $commands === [] ? '  (none)' : implode("\n", $commands),
        );

        $this->api->messages->send(
            MessageBuilder::new()
                ->setChat($update->getChatId())
                ->setText($text)
                ->setFormat(Format::Markdown),
        );
    }

    private function patchBot(MessageCreatedUpdate $update, ParsedCommand $command): void
    {
        $name = $command->arg(0);
        if ($name === null || $name === '') {
            $this->replyMarkdown($update, 'Usage: `/bot_patch <newName>`');
            return;
        }
        $patched = $this->api->bots->patchBot(new BotPatch(name: $name));
        $this->replyMarkdown($update, sprintf('Bot name updated to *%s*', $patched->name));
    }
}
