<?php

declare(strict_types=1);

namespace Autogedal\RemoveSubscriber\Model;

use Mktr\Tracker\Model\Api as TheMarketerApi;
use Psr\Log\LoggerInterface;

class RemoveSubscriberService
{
    public function __construct(
        private readonly TheMarketerApi $api,
        private readonly LoggerInterface $logger
    ) {
    }

    public function execute(string $email): void
    {
        $this->call('remove_subscriber', $email);
    }

    public function anonymize(string $email): void
    {
        $this->call('anonymize-email', $email);
    }

    private function call(string $endpoint, string $email): void
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return;
        }

        try {
            $this->api->send($endpoint, ['email' => $email]);
        } catch (\Throwable $e) {
            $this->logger->error(
                sprintf('TheMarketer %s failed for [sha256:%s]: %s', $endpoint, hash('sha256', $email), $e->getMessage()),
                ['exception' => $e]
            );
        }
    }
}
