<?php

declare(strict_types=1);

namespace PhpWA\Client;

use PhpWA\Auth\AuthenticationCredentials;
use PhpWA\Exception\ProtocolException;
use PhpWA\Protocol\Binary\BinaryNode;

final class MessageReceiptBuilder
{
    public function delivery(IncomingMessageEnvelope $envelope, AuthenticationCredentials $credentials): BinaryNode
    {
        $attrs = ['id' => $envelope->id(), 'to' => $envelope->chatJid()];
        if ($envelope->isGroup() && $envelope->participantJid() !== null) {
            $attrs['participant'] = $envelope->participantJid();
        }
        if ($envelope->category() === 'peer') {
            $attrs['type'] = 'peer_msg';
        } elseif ($envelope->isFromMe()) {
            $attrs['type'] = 'sender';
        }
        if (!$credentials->me()) { throw new ProtocolException('Cannot build a receipt for an unpaired account.'); }
        return new BinaryNode('receipt', $attrs);
    }
}
