<?php

declare(strict_types=1);

namespace App\Scenario;

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

final class DebugScenario extends AbstractScenario
{
    public function handle(MessageCreatedUpdate $update, ParsedCommand $command): void
    {
        $mode = $command->arg(0, 'status');
        $debugChatId = $this->api->debugs->getChatId();

        switch ($mode) {
            case 'on':
                $this->api->debugs->withChatId($update->getChatId());
                $this->replyMarkdown($update, 'Debugs enabled in this chat. Send `/debug raw` to dump next update, `/debug err` to push a synthetic error.');
                return;
            case 'off':
                // We can't null out chatId from outside (no setter back to null); re-create Api via options.
                // Workaround: send a notice. The library does not currently expose unsetChatId().
                $this->replyMarkdown($update, 'To disable debugs, set DEBUG_CHAT_ID= in .env and restart the container.');
                return;
            case 'raw':
                if ($debugChatId === null) {
                    $this->replyMarkdown($update, 'Debugs not enabled. Run `/debug on` first.');
                    return;
                }
                $this->api->debugs->sendText('raw dump: ' . $update->getDebugRaw());
                $this->replyMarkdown($update, 'Sent raw update JSON to debug chat.');
                return;
            case 'err':
                if ($debugChatId === null) {
                    $this->replyMarkdown($update, 'Debugs not enabled. Run `/debug on` first.');
                    return;
                }
                $this->api->debugs->sendErr(new \RuntimeException('synthetic error from /debug err'));
                $this->replyMarkdown($update, 'Sent synthetic error to debug chat.');
                return;
            case 'status':
            default:
                $this->api->messages->send(
                    MessageBuilder::new()
                        ->setChat($update->getChatId())
                        ->setText(sprintf('Debug chat: %s', $debugChatId === null ? '(disabled)' : "`$debugChatId`"))
                        ->setFormat(Format::Markdown),
                );
        }
    }
}
