<?php

declare(strict_types=1);

namespace PhpWA\Client;

use InvalidArgumentException;
use PhpWA\Runtime\Deadline;

final class OutgoingReplayWorker
{
      private $accountId;
      private $connection;
      private $outgoing;

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

     
    public function replay(Deadline $deadline, int $limit = 100): array
    {
        if ($limit < 1 || $limit > 1000) { throw new InvalidArgumentException('Replay limit is invalid.'); }
        $sent = [];
        foreach ($this->outgoing->pending($this->accountId, $limit) as $id => $stanza) {
            $this->connection->send($stanza, $deadline);
            $sent[] = $id;
        }
        return $sent;
    }
}
