<?php

declare(strict_types=1);

namespace PhpWA\Client;

use InvalidArgumentException;
use PhpWA\Protocol\Jid\Jid;

final class GroupMetadata
{
      private $groupJid;
      private $participants;
      private $addressingMode;
      private $phoneToLid;

     
    public function __construct(string $groupJid, array $participants, string $addressingMode, array $phoneToLid = [])
    {
        $group = Jid::parse($groupJid);
        if (!$group instanceof Jid || !$group->isGroup() || $group->device() !== null
            || ($addressingMode !== 'pn' && $addressingMode !== 'lid')
            || $participants === [] || count($participants) > 5000) {
            throw new InvalidArgumentException('Group metadata header is invalid.');
        }
        $unique = [];
        foreach ($participants as $value) {
            $jid = is_string($value) ? Jid::parse($value) : null;
            if (!$jid instanceof Jid || (!$jid->isPhoneNumber() && !$jid->isLid()
                && !$jid->isHostedPhoneNumber() && !$jid->isHostedLid())) {
                throw new InvalidArgumentException('Group metadata contains an invalid participant.');
            }
            $unique[(string) new Jid($jid->user(), $jid->server(), null, $jid->domainType())] = true;
        }
         
         
        $validated = new DeviceDiscoveryResult([], $phoneToLid);
        $this->groupJid = (string) $group; $this->participants = array_keys($unique);
        $this->addressingMode = $addressingMode; $this->phoneToLid = $validated->phoneToLid();
    }

    public function groupJid(): string { return $this->groupJid; }
      public function participants(): array { return $this->participants; }
    public function addressingMode(): string { return $this->addressingMode; }
      public function phoneToLid(): array { return $this->phoneToLid; }
}
