<?php

declare(strict_types=1);

namespace Autogedal\RemoveSubscriber\Plugin;

use Amasty\Gdpr\Model\Anonymization\Anonymizer;
use Autogedal\Extend\Model\TheMarketer\SyncContext;
use Autogedal\RemoveSubscriber\Model\RemoveSubscriberService;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Psr\Log\LoggerInterface;

class GdprAnonymizePlugin
{
    public function __construct(
        private readonly RemoveSubscriberService $removeSubscriberService,
        private readonly CustomerRepositoryInterface $customerRepository,
        private readonly SyncContext $syncContext,
        private readonly LoggerInterface $logger
    ) {
    }

    public function aroundAnonymizeCustomer(
        Anonymizer $subject,
        callable $proceed,
        int $customerId,
        $isDeleting = false
    ): void {
        $email = $this->getCustomerEmail($customerId);

        $this->syncContext->setIsGdprAnonymization(true);
        try {
            $proceed($customerId, $isDeleting);
        } finally {
            $this->syncContext->setIsGdprAnonymization(false);
        }

        if ($email) {
            $this->removeSubscriberService->anonymize($email);
        }
    }

    private function getCustomerEmail(int $customerId): ?string
    {
        try {
            return $this->customerRepository->getById($customerId)->getEmail();
        } catch (\Throwable $e) {
            $this->logger->warning(
                sprintf('RemoveSubscriber: could not load customer %d before GDPR anonymization: %s', $customerId, $e->getMessage())
            );
            return null;
        }
    }
}
