<?php

declare(strict_types=1);

namespace App\Handler\Update;

use App\Handler\AbstractUpdateHandler;
use App\Keyboard\KeyboardFactory;
use Pkirillw\MaxBotApi\Api;
use Pkirillw\MaxBotApi\Builder\Message as MessageBuilder;
use Pkirillw\MaxBotApi\Scheme\CallbackAnswer;
use Pkirillw\MaxBotApi\Scheme\Enum\Format;
use Pkirillw\MaxBotApi\Scheme\Update\MessageCallbackUpdate;
use Pkirillw\MaxBotApi\Scheme\Update\UpdateInterface;
use Psr\Log\LoggerInterface;

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

    public function handle(UpdateInterface $update): void
    {
        if (!$update instanceof MessageCallbackUpdate) {
            return;
        }
        $callback = $update->callback;
        $this->logger->info('callback: ' . $callback->payload, [
            'callback_id' => $callback->callbackId,
            'user_id' => $callback->user?->userId ?? 0,
        ]);

        // 1. answerOnCallback — show a notification toast.
        $this->api->messages->answerOnCallback(
            $callback->callbackId,
            new CallbackAnswer(notification: 'Нажата кнопка: ' . $callback->payload),
        );

        // 2. also send a regular chat message so the interaction is visible in history.
        $chatId = $update->getChatId();
        if ($chatId > 0) {
            $this->api->messages->send(
                MessageBuilder::new()
                    ->setChat($chatId)
                    ->setText(sprintf('*Клик по кнопке*\npayload: `%s`', $callback->payload))
                    ->setFormat(Format::Markdown),
            );
        }
    }
}
