<?php

declare(strict_types=1);

namespace App\Handler\Update;

use App\Handler\AbstractUpdateHandler;
use App\Scenario\HelpScenario;
use App\Util\ParsedCommand;
use Pkirillw\MaxBotApi\Api;
use Pkirillw\MaxBotApi\Scheme\Update\BotStartedUpdate;
use Pkirillw\MaxBotApi\Scheme\Update\UpdateInterface;
use Psr\Log\LoggerInterface;

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

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

    public function handle(UpdateInterface $update): void
    {
        if (!$update instanceof BotStartedUpdate) {
            return;
        }
        $this->logger->info('bot started', [
            'chat_id' => $update->chatId,
            'user_id' => $update->user->userId,
            'payload' => $update->payload,
        ]);

        // Build a synthetic MessageCreatedUpdate-like ParsedCommand so HelpScenario handles it.
        $dummy = new \Pkirillw\MaxBotApi\Scheme\Update\MessageCreatedUpdate(
            message: $update->user->userId ? new \Pkirillw\MaxBotApi\Scheme\Message(
                sender: $update->user,
                recipient: new \Pkirillw\MaxBotApi\Scheme\Recipient(chatId: $update->chatId, userId: $update->user->userId),
            ) : new \Pkirillw\MaxBotApi\Scheme\Message(),
            timestamp: $update->timestamp,
            debugRaw: $update->debugRaw,
        );
        $command = new ParsedCommand(name: 'help', args: [], raw: '/help', tail: '');
        $this->help->handle($dummy, $command);
    }
}
