<?php

namespace App\DTOs;

class TelegramMessage
{
    public function __construct(
        public readonly int $chatId,
        public readonly int $userId,
        public readonly string $text,
        public readonly array $message,
        public readonly ?array $contact = null,
        public readonly ?array $location = null
    ) {}

    public static function fromArray(array $message): self
    {
        return new self(
            chatId: $message['chat']['id'] ?? 0,
            userId: $message['from']['id'] ?? 0,
            text: $message['text'] ?? '',
            message: $message,
            contact: $message['contact'] ?? null,
            location: $message['location'] ?? null
        );
    }

    public function hasContact(): bool
    {
        return $this->contact !== null;
    }

    public function hasLocation(): bool
    {
        return $this->location !== null;
    }

    public function isCommand(): bool
    {
        return str_starts_with($this->text, '/');
    }

    public function getCommand(): ?string
    {
        if (!$this->isCommand()) {
            return null;
        }

        $parts = explode(' ', $this->text, 2);
        return ltrim($parts[0], '/');
    }

    public function getCommandArgs(): array
    {
        if (!$this->isCommand()) {
            return [];
        }

        $parts = explode(' ', $this->text, 2);
        if (count($parts) < 2) {
            return [];
        }

        return array_filter(explode(' ', $parts[1]));
    }
}