<?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 PhoneCheckScenario extends AbstractScenario
{
    public function handle(MessageCreatedUpdate $update, ParsedCommand $command): void
    {
        switch ($command->name) {
            case 'phone_check':
                $this->checkPhone($update, $command);
                return;
            case 'phone_list':
                $this->listPhones($update, $command);
                return;
        }
    }

    private function checkPhone(MessageCreatedUpdate $update, ParsedCommand $command): void
    {
        $phone = $command->arg(0, '70001234567');
        $msg = MessageBuilder::new()
            ->setChat($update->getChatId())
            ->setPhoneNumbers([$phone]);
        $exists = $this->api->messages->check($msg);
        $this->replyMarkdown($update, sprintf('`check(%s)` → %s', $phone, $exists ? 'exists' : 'not found'));
    }

    private function listPhones(MessageCreatedUpdate $update, ParsedCommand $command): void
    {
        $raw = $command->arg(0, '70001234567,70009990000');
        $phones = array_values(array_filter(explode(',', $raw)));
        $msg = MessageBuilder::new()
            ->setChat($update->getChatId())
            ->setPhoneNumbers($phones);
        $existing = $this->api->messages->listExist($msg);
        $this->api->messages->send(
            MessageBuilder::new()
                ->setChat($update->getChatId())
                ->setText(sprintf(
                    "*listExist*\ninput: `%s`\nfound (%d): `%s`",
                    implode(', ', $phones),
                    count($existing),
                    implode('`, `', $existing),
                ))
                ->setFormat(Format::Markdown),
        );
    }
}
