<?php

declare(strict_types=1);

namespace Autogedal\RemoveSubscriber\Plugin;

use Autogedal\RemoveSubscriber\Model\RemoveSubscriberService;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterface;
use Psr\Log\LoggerInterface;

class CustomerDeletePlugin
{
    public function __construct(
        private readonly RemoveSubscriberService $removeSubscriberService,
        private readonly LoggerInterface $logger
    ) {
    }

    public function aroundDelete(
        CustomerRepositoryInterface $subject,
        callable $proceed,
        CustomerInterface $customer
    ): bool {
        $email = $customer->getEmail();
        $result = $proceed($customer);

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

        return $result;
    }

    public function aroundDeleteById(
        CustomerRepositoryInterface $subject,
        callable $proceed,
        int $customerId
    ): bool {
        $email = $this->getCustomerEmail($subject, $customerId);
        $result = $proceed($customerId);

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

        return $result;
    }

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