<?php declare(strict_types=1);
defined('MW_PATH') or exit('No direct script access allowed');

use Interop\Queue\Context;
use Interop\Queue\Message;
use Interop\Queue\Processor;

/**
 * @package MailWizz EMA
 * @author MailWizz Development Team <support@mailwizz.com>
 * @link https://www.mailwizz.com/
 * @copyright MailWizz EMA (https://www.mailwizz.com)
 * @license https://www.mailwizz.com/license/
 * @since 2.0.0
 */

class QueueProcessorBackendListsAllSubscribersFilterUnsubscribe implements Processor
{
    /**
     * @param Message $message
     * @param Context $context
     *
     * @return string
     */
    public function process(Message $message, Context $context)
    {
        // do not retry this message
        if ($message->isRedelivered()) {
            return self::ACK;
        }

        $filter = new AllCustomersListsSubscribersFilters();

        $attributes = CMap::mergeArray($filter->getAttributes(), $message->getProperties());
        foreach ($attributes as $key => $value) {
            if ($filter->hasAttribute($key) || property_exists($filter, $key)) {
                $filter->$key = $value;
            }
        }

        $user = User::model()->findByPk((int)$filter->user_id);
        if (empty($user)) {
            return self::ACK;
        }

        $filter->unsubscribeSubscribers();

        $message = new UserMessage();
        $message->user_id = (int)$filter->user_id;
        $message->title   = 'Unsubscribe subscribers';
        $message->message = 'Action completed successfully!';
        $message->save();

        return self::ACK;
    }
}
