<?php

declare(strict_types=1);

namespace PhpWA\Transport;

use InvalidArgumentException;
use PhpWA\Exception\ProtocolException;

final class FrameCodec
{
    public const MAX_WIRE_LENGTH = 16777215;

    public static function routingHeader(int $major = 6, int $dictionaryVersion = 3): string
    {
        if ($major < 0 || $major > 255 || $dictionaryVersion < 0 || $dictionaryVersion > 255) {
            throw new InvalidArgumentException('WA routing-header bytes must fit one byte.');
        }
        return 'WA' . chr($major) . chr($dictionaryVersion);
    }

    public static function encode(string $payload, bool $withHeader = false, int $maxLength = self::MAX_WIRE_LENGTH): string
    {
        $length = strlen($payload);
        if ($length > $maxLength || $length > self::MAX_WIRE_LENGTH) {
            throw new ProtocolException('WhatsApp frame exceeds configured limit.');
        }
        $prefix = chr(($length >> 16) & 255) . chr(($length >> 8) & 255) . chr($length & 255);
        return ($withHeader ? self::routingHeader() : '') . $prefix . $payload;
    }

    private function __construct()
    {
    }
}
