<?php

declare(strict_types=1);

namespace App\Handler\Update;

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

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

    public function handle(UpdateInterface $update): void
    {
        if (!$update instanceof UserAddedToChatUpdate) {
            return;
        }
        $this->logger->info('user added to chat', [
            'chat_id' => $update->chatId,
            'added_user_id' => $update->user->userId,
            'by_inviter_id' => $update->inviterId,
        ]);
        $name = $update->user->name ?: ('user #' . $update->user->userId);
        $this->api->messages->send(
            MessageBuilder::new()
                ->setChat($update->chatId)
                ->setText(sprintf('👋 Добро пожаловать, *%s*!', $name))
                ->setFormat(Format::Markdown),
        );
    }
}
