<?php

declare(strict_types=1);

namespace App\Handler\Update;

use App\Handler\AbstractUpdateHandler;
use App\Keyboard\KeyboardFactory;
use App\Scenario\HelpScenario;
use App\Util\CommandRouter;
use App\Util\ParsedCommand;
use Pkirillw\MaxBotApi\Api;
use Pkirillw\MaxBotApi\Scheme\Update\MessageCreatedUpdate;
use Psr\Log\LoggerInterface;

final class MessageCreatedHandler extends AbstractUpdateHandler
{
    public function updateClass(): string { return \Pkirillw\MaxBotApi\Scheme\Update\MessageCreatedUpdate::class; }

    public function __construct(
        Api $api,
        LoggerInterface $logger,
        KeyboardFactory $keyboards,
        private CommandRouter $router,
        private HelpScenario $help,
    ) {
        parent::__construct($api, $logger, $keyboards);
    }

    public function handle(\Pkirillw\MaxBotApi\Scheme\Update\UpdateInterface $update): void
    {
        if (!$update instanceof MessageCreatedUpdate) {
            return;
        }
        $command = ParsedCommand::parse($update->getText());

        if ($command === null) {
            // Free-text message — echo it back so the bot feels alive in dialog mode.
            $senderName = $update->message->sender?->name ?? 'незнакомец';
            $this->api->messages->send(
                \Pkirillw\MaxBotApi\Builder\Message::new()
                    ->setChat($update->getChatId())
                    ->setText(sprintf('Привет, %s! Я бот-демо. Набери /help для списка команд.', $senderName)),
            );
            return;
        }

        $this->logger->info('command: ' . $command->name, ['args' => $command->args]);

        if ($command->name === 'start') {
            $this->help->handle($update, $command);
            return;
        }

        if (!$this->router->route($update, $command)) {
            $this->help->handleUnknown($update, $command);
        }
    }
}
