<?php

declare(strict_types=1);

namespace PhpWA\Client;

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

final class OutgoingAckProcessor
{
      private $accountId;
      private $outgoing;

    public function __construct(string $accountId, OutgoingStanzaStore $outgoing)
    {
        if ($accountId === '' || strlen($accountId) > 512 || preg_match('//u', $accountId) !== 1) {
            throw new \InvalidArgumentException('Outgoing ACK account ID is invalid.');
        }
        $this->accountId = $accountId; $this->outgoing = $outgoing;
    }

     
    public function process(BinaryNode $node): bool
    {
        if ($node->tag() !== 'ack' || $node->attribute('class') !== 'message') { return false; }
        $id = $node->attribute('id');
        if ($id === null || preg_match('/\A[A-Za-z0-9._:-]{1,256}\z/D', $id) !== 1) {
            throw new ProtocolException('Outgoing message ACK has an invalid ID.');
        }
        $error = $node->attribute('error');
        if ($error !== null && $error !== '0') {
            throw new ProtocolException('WhatsApp rejected an outgoing message stanza.');
        }
        $this->outgoing->complete($this->accountId, $id);
        return true;
    }
}
