<?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\Helper\Data;
use FiloBlu\ActiveCampaign\Model\Resource\ActiveCampaign;
use Magento\Framework\Event\Observer;
use Psr\Log\LoggerInterface;

/**
 * @class BirthdayCoupon
 * @package FiloBlu\ActiveCampaign\Observer
 */
class BirthdayCoupon extends AbstractObserver
{

    /**
     * @var ActiveCampaign
     */
    private $activeCampaign;

    /**
     * @param LoggerInterface $logger
     * @param JobsRepositoryInterface $jobsRepository
     * @param JobsInterfaceFactory $jobsFactory
     * @param Data $helperData
     * @param ActiveCampaign $activeCampaign
     */
    public function __construct(
        LoggerInterface         $logger,
        JobsRepositoryInterface $jobsRepository,
        JobsInterfaceFactory    $jobsFactory,
        Data                    $helperData,
        ActiveCampaign          $activeCampaign
    ) {
        $this->activeCampaign = $activeCampaign;
        parent::__construct($logger, $jobsRepository, $jobsFactory, $helperData);
    }

    /**
     * @param Observer $observer
     * @throws Exception
     * @event filoblu_birthday_coupon_generate_after
     */
    public function execute(Observer $observer)
    {
        if ((!$bulkData = $observer->getData('bulkData')) || (!$type = $observer->getData('type'))) {
            return;
        }

        $payload = $this->helperData->generateBulkPayloadForBirthdayCoupon($bulkData, $type);
        if (empty($payload)) {
            return;
        }

        $this->activeCampaign->sendSubscriberWithBulk($payload);
    }
}
