<?php
declare(strict_types=1);
namespace FiloBlu\ActiveCampaign\Observer;

use Exception;
use FiloBlu\ActiveCampaign\Api\Data\JobsInterfaceFactory;
use FiloBlu\ActiveCampaign\Api\JobsRepositoryInterface;
use FiloBlu\ActiveCampaign\Model\Config\Source\DirectionType;
use FiloBlu\ActiveCampaign\Model\Config\Source\EntityType;
use FiloBlu\ActiveCampaign\Model\Config\Source\JobStatus;
use FiloBlu\ActiveCampaign\Model\Config\Source\Type;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Newsletter\Model\SubscriberFactory;
use Psr\Log\LoggerInterface;

class RevokeSubscriptionObserver implements ObserverInterface
{
    /**
     * @var JobsRepositoryInterface
     */
    private $jobsRepository;

    /**
     * @var JobsInterfaceFactory
     */
    private $jobsFactory;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var SubscriberFactory
     */
    private $subscriberFactory;

    /**
     * RevokeSubscriptionObserver constructor.
     * @param JobsRepositoryInterface $jobsRepository
     * @param JobsInterfaceFactory $jobsFactory
     * @param LoggerInterface $logger
     * @param SubscriberFactory $subscriberFactory
     */
    public function __construct(
        JobsRepositoryInterface $jobsRepository,
        JobsInterfaceFactory    $jobsFactory,
        LoggerInterface         $logger,
        SubscriberFactory       $subscriberFactory
    ) {
        $this->jobsRepository = $jobsRepository;
        $this->jobsFactory = $jobsFactory;
        $this->logger = $logger;
        $this->subscriberFactory = $subscriberFactory;
    }

    /**
     * Execute the observer logic
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        $subscription = $observer->getEvent()->getData('subscription');
        $entityId = $this->getEntityId($subscription);
        $entity = $this->getEntity($subscription);

        if ($entityId && $entity) {
            $this->writeJob($entityId, $entity);
        }
    }

    /**
     * Get the entity ID
     *
     * @param $subscription
     * @return int|null
     */
    private function getEntityId($subscription): ?int
    {
        if ($subscription->getCustomerId() != 0) {
            return $subscription->getCustomerId();
        }

        try {
            $subscriber = $this->subscriberFactory->create();
            $subscriber->loadByEmail($subscription->getEmail());

            if ($subscriber->getId()) {
                return $subscriber->getId();
            } else {
                $this->logger->error(sprintf('Subscriber not found for email: %s', $subscription->getEmail()));
                return null;
            }
        } catch (Exception $e) {
            $this->logger->error($e->getMessage());
            return null;
        }
    }

    /**
     * Get the entity type
     *
     * @param $subscription
     * @return string
     */
    private function getEntity($subscription): string
    {
        if ($subscription->getCustomerId() != 0) {
            return EntityType::ENTITY_CUSTOMER;
        }
        return EntityType::ENTITY_SUBSCRIBER;
    }

    /**
     * Create and save the job
     *
     * @param int $entityId
     * @param string $entity
     * @return void
     */
    private function writeJob(int $entityId, string $entity): void
    {
        try {
            $job = $this->jobsFactory->create();
            $job->setEntity($entity)
                ->setEntityId($entityId)
                ->setDirection(DirectionType::DIRECTION_EXPORT)
                ->setType(Type::TYPE_REST)
                ->setStatus(JobStatus::JOB_STATUS_WAITING);
            $this->jobsRepository->save($job);
        } catch (Exception $e) {
            $this->logger->error($e->getMessage());
        }
    }
}
