<?php

declare(strict_types=1);

namespace PhpWA\Auth;

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

final class AccountIdentity
{
      private $id;
      private $name;
      private $lid;

    public function __construct(string $id, ?string $name = null, ?string $lid = null)
    {
        $accountJid = Jid::parse($id);
        if (!$accountJid instanceof Jid || (!$accountJid->isPhoneNumber() && !$accountJid->isHostedPhoneNumber())
            || preg_match('/^[1-9][0-9]{0,19}$/D', $accountJid->user()) !== 1) {
            throw new InvalidArgumentException('Account identity must be a numeric WhatsApp phone JID.');
        }
        if ($lid !== null) {
            $lidJid = Jid::parse($lid);
            if (!$lidJid instanceof Jid || (!$lidJid->isLid() && !$lidJid->isHostedLid())
                || preg_match('/^[1-9][0-9]{0,19}$/D', $lidJid->user()) !== 1) {
                throw new InvalidArgumentException('Account LID is invalid.');
            }
        }
        if ($name !== null && (strlen($name) > 512 || preg_match('//u', $name) !== 1)) {
            throw new InvalidArgumentException('Account display name is invalid.');
        }
        $this->id = $id;
        $this->name = $name;
        $this->lid = $lid;
    }

    public function id(): string { return $this->id; }
    public function name(): ?string { return $this->name; }
    public function lid(): ?string { return $this->lid; }
    public function withLid(?string $lid): self { return new self($this->id, $this->name, $lid); }
}
