<?php
declare(strict_types=1);

namespace FreshCloud\Mail\BaseUtils;

use InvalidArgumentException;

final readonly class EmailAddress
{
    public function __construct(
        public ?string $displayName,
        public string $address
    ) {
        if (!filter_var($address, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException("Invalid email address: {$address}");
        }
    }

    public function __toString(): string
    {
        return $this->displayName === null 
            ? $this->address 
            : sprintf('"%s" <%s>', $this->displayName, $this->address);
    }

    public static function parse(string $raw): self
    {
        if (preg_match('/^(?:"?([^"]+?)"?\s*)?<([^>]+)>$/', $raw, $matches)) {
            return new self(trim($matches[1] ?? ''), trim($matches[2]));
        }
        
        return new self(null, trim($raw));
    }
}