<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 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 CpCreation\VitiCore\Marketing\Model;

use CpCreation\VitiCore\Behavior\HasTimestamp;
use CpCreation\VitiCore\Behavior\Impl\Timestamp;
use CpCreation\VitiCore\Marketing\Repository\ReviewSolicitationOptOutRepository;
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;

#[ORM\Entity(repositoryClass: ReviewSolicitationOptOutRepository::class)]
#[ORM\Table(name: 'marketing_review_solicitation_opt_out')]
#[ORM\UniqueConstraint(name: 'uniq_marketing_review_opt_out_email_hash', columns: ['email_hash'])]
#[ORM\Index(name: 'marketing_review_opt_out_source_idx', columns: ['source_invitation_id'])]
#[ORM\HasLifecycleCallbacks]
class ReviewSolicitationOptOut implements HasTimestamp
{
    use Timestamp;

    #[ORM\Id]
    #[ORM\Column(type: 'uuid')]
    #[ORM\GeneratedValue(strategy: 'NONE')]
    private UuidInterface $id;

    #[ORM\Column(type: 'string', length: 64)]
    private string $emailHash;

    #[ORM\ManyToOne(targetEntity: ReviewInvitation::class)]
    #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
    private ?ReviewInvitation $sourceInvitation;

    public function __construct(string $email, ?ReviewInvitation $sourceInvitation = null)
    {
        $this->id = Uuid::uuid4();
        $this->emailHash = self::hashEmail($email);
        $this->sourceInvitation = $sourceInvitation;
    }

    public function getId(): UuidInterface
    {
        return $this->id;
    }

    public function getEmailHash(): string
    {
        return $this->emailHash;
    }

    public function getSourceInvitation(): ?ReviewInvitation
    {
        return $this->sourceInvitation;
    }

    public function matches(string $email): bool
    {
        return hash_equals($this->emailHash, self::hashEmail($email));
    }

    public static function hashEmail(string $email): string
    {
        $normalizedEmail = mb_strtolower(mb_trim($email));
        if (false === filter_var($normalizedEmail, \FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('L’adresse e-mail de l’opposition aux sollicitations est invalide.');
        }

        return hash('sha256', $normalizedEmail);
    }
}
