<?php

namespace KupShop\KupShopBundle\Util\Mail;

use Composer\InstalledVersions;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
use KupShop\KupShopBundle\Util\Mail\Validation\DiacriticValidation;
use KupShop\KupShopBundle\Util\Mail\Validation\DNSCheckValidation;
use Psr\Log\LoggerInterface;

class EmailCheck
{
    private $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function isEmailDomainValid(string $email): bool
    {
        $emailValidator = new EmailValidator();

        $version = InstalledVersions::getVersion('egulias/email-validator');

        if ((int) $version[0] >= 3) {
            $validations = new MultipleValidationWithAnd([
                new NoRFCWarningsValidation(),
                new DNSCheckValidation(),
                new DiacriticValidation(),
            ]);
        } else {
            $validations = new MultipleValidationWithAnd([
                new NoRFCWarningsValidation(),
                new \Egulias\EmailValidator\Validation\DNSCheckValidation(),
            ]);
        }

        if (!$emailValidator->isValid($email, $validations)) {
            $this->log($email);

            return false;
        }

        return true;
    }

    /**
     * Log to Kibana.
     */
    private function log($email)
    {
        $this->logger->warning(
            'Invalid e-mail domain',
            [
                'email' => $email,
            ]
        );
    }
}
