<?php

declare(strict_types=1);

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\CoreBundle\Shared\ValueObject;

use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Embeddable]
class AddressEmail implements \Stringable
{
    protected string $prefix;
    protected string $domain;

    #[Assert\NotBlank]
    #[Assert\Email]
    #[ORM\Column(name: 'email', type: Types::STRING)]
    public string $email;

    #[ORM\Column(name: 'name', type: Types::STRING, nullable: true)]
    public ?string $name = null;

    public function __construct(string $email, ?string $name = null)
    {
        $delimiter = mb_strrpos($email, '@');
        if (false === $delimiter) {
            throw new \InvalidArgumentException('Invalid email format: missing "@" character.');
        }
        $this->prefix = mb_substr($email, 0, $delimiter);
        $this->domain = mb_substr($email, $delimiter + 1);
        $this->email = $email;
        $this->name = $name;
    }

    public function getPrefix(): string
    {
        return $this->prefix;
    }

    public function getDomain(): string
    {
        return $this->domain;
    }

    public function isEqual(self $addressEmail): bool
    {
        return $addressEmail->email === $this->email && $addressEmail->name === $this->name;
    }

    public function __toString(): string
    {
        return $this->email;
    }
}
