<?php

declare(strict_types=1);

namespace App\Framework\Notification\Channels\Telegram\ValueObjects;

/**
 * Telegram Inline Keyboard Value Object
 *
 * Represents an inline keyboard with action buttons
 */
final readonly class InlineKeyboard
{
    /**
     * @param array<array<InlineKeyboardButton>> $rows Rows of buttons
     */
    public function __construct(
        public array $rows
    ) {
        if (empty($rows)) {
            throw new \InvalidArgumentException('Inline keyboard must have at least one row');
        }

        foreach ($rows as $row) {
            if (empty($row)) {
                throw new \InvalidArgumentException('Keyboard row cannot be empty');
            }

            foreach ($row as $button) {
                if (!$button instanceof InlineKeyboardButton) {
                    throw new \InvalidArgumentException('All buttons must be InlineKeyboardButton instances');
                }
            }
        }
    }

    /**
     * Create keyboard with a single row of buttons
     */
    public static function singleRow(InlineKeyboardButton ...$buttons): self
    {
        return new self([$buttons]);
    }

    /**
     * Create keyboard with multiple rows
     *
     * @param array<array<InlineKeyboardButton>> $rows
     */
    public static function multiRow(array $rows): self
    {
        return new self($rows);
    }

    /**
     * Convert to Telegram API format
     */
    public function toArray(): array
    {
        $keyboard = [];

        foreach ($this->rows as $row) {
            $keyboardRow = [];
            foreach ($row as $button) {
                $keyboardRow[] = $button->toArray();
            }
            $keyboard[] = $keyboardRow;
        }

        return ['inline_keyboard' => $keyboard];
    }

    /**
     * Get total number of buttons
     */
    public function getButtonCount(): int
    {
        $count = 0;
        foreach ($this->rows as $row) {
            $count += count($row);
        }
        return $count;
    }
}
