<?php

namespace App\DTOs;

class TelegramCallback
{
    public function __construct(
        public readonly int $chatId,
        public readonly int $userId,
        public readonly string $data,
        public readonly string $callbackQueryId,
        public readonly array $callbackQuery
    ) {}

    public static function fromArray(array $callbackQuery): self
    {
        return new self(
            chatId: $callbackQuery['message']['chat']['id'] ?? 0,
            userId: $callbackQuery['from']['id'] ?? 0,
            data: $callbackQuery['data'] ?? '',
            callbackQueryId: $callbackQuery['id'] ?? '',
            callbackQuery: $callbackQuery
        );
    }

    public function getAction(): ?string
    {
        if (!str_contains($this->data, ':')) {
            return null;
        }

        $parts = explode(':', $this->data, 3);
        return $parts[1] ?? null;
    }

    public function getPayload(): ?string
    {
        if (!str_contains($this->data, ':')) {
            return null;
        }

        $parts = explode(':', $this->data, 3);
        return $parts[2] ?? null;
    }

    public function getPrefix(): ?string
    {
        if (!str_contains($this->data, ':')) {
            return null;
        }

        $parts = explode(':', $this->data, 3);
        return $parts[0] ?? null;
    }

    public function isForModule(string $modulePrefix): bool
    {
        return $this->getPrefix() === $modulePrefix;
    }
}