<?php

namespace App\EventListener;

use App\Entity\DomainEmail;
use App\Service\EsyMailService;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Events;
use Psr\Log\LoggerInterface;

#[AsEntityListener(event: Events::postPersist, entity: DomainEmail::class)]
#[AsEntityListener(event: Events::postUpdate, entity: DomainEmail::class)]
#[AsEntityListener(event: Events::postRemove, entity: DomainEmail::class)]
class DomainEmailSyncListener
{
    public function __construct(
        private EsyMailService $esyMail,
        private LoggerInterface $logger,
    ) {
    }

    public function postPersist(DomainEmail $email): void
    {
        if (!$this->esyMail->isAvailable()) {
            return;
        }

        $fullEmail = $email->getFullEmail();
        $domain = $email->getDomain()->getFqdn();

        if (!$this->esyMail->domainExists($domain)) {
            $this->esyMail->createDomain($domain);
        }

        $tempPassword = bin2hex(random_bytes(8));

        if ($this->esyMail->createMailbox($fullEmail, $tempPassword, $email->getName(), $email->getQuotaMb())) {
            $this->logger->info('EsyMail sync: boite creee '.$fullEmail);
        }
    }

    public function postUpdate(DomainEmail $email): void
    {
        if (!$this->esyMail->isAvailable()) {
            return;
        }

        $fullEmail = $email->getFullEmail();

        if (!$this->esyMail->mailboxExists($fullEmail)) {
            return;
        }

        $this->esyMail->updateMailbox($fullEmail, $email->getName(), $email->getQuotaMb(), $email->isActive());
        $this->logger->info('EsyMail sync: boite mise a jour '.$fullEmail);
    }

    public function postRemove(DomainEmail $email): void
    {
        if (!$this->esyMail->isAvailable()) {
            return;
        }

        $fullEmail = $email->getFullEmail();

        if ($this->esyMail->deleteMailbox($fullEmail)) {
            $this->logger->info('EsyMail sync: boite supprimee '.$fullEmail);
        }
    }
}
