<?php

declare(strict_types=1);

namespace PhpWA\Client;

use InvalidArgumentException;
use PhpWA\Runtime\Deadline;

final class OutgoingReplayWorker
{
    /** @var string */ private $accountId;
    /** @var ProtocolConnectionInterface */ private $connection;
    /** @var OutgoingStanzaStore */ 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;
    }

    /** @return list<string> IDs submitted again; they remain pending until server ACK. */
    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;
    }
}
