<?php

declare(strict_types=1);

namespace PhpWA\Auth;

use InvalidArgumentException;

final class QrPayloadBuilder
{
    public function build(
        string $reference,
        AuthenticationCredentials $credentials,
        ?CompanionDeviceConfig $config = null
    ): string
    {
        if ($reference === '' || strlen($reference) > 4096 || preg_match('//u', $reference) !== 1 || preg_match('/[,\x00-\x1f\x7f]/', $reference)) {
            throw new InvalidArgumentException('WhatsApp QR reference is invalid.');
        }
        $config = $config ?? new CompanionDeviceConfig();
        return 'https://wa.me/settings/linked_devices#' . implode(',', [
            $reference,
            base64_encode($credentials->noiseKey()->publicKey()),
            base64_encode($credentials->signedIdentityKey()->publicKey()),
            base64_encode($credentials->advSecretKey()),
            (string) CompanionPlatform::qrClientId($config),
        ]);
    }
}
