<?php

namespace FiloBlu\Esb\Model\Producer;

use FiloBlu\Esb\Api\Data\MessageInterface;
use FiloBlu\Esb\Api\Data\StatusInterface;
use FiloBlu\Esb\Core\Extractor\ObjectTypeFromMessage;
use Magento\Framework\DataObject;
use Magento\Sales\Api\Data\CreditmemoInterface;

/**
 * Class CreditMemoSaveAfterProducer
 * @package FiloBlu\Esb\Model\Producer
 */
class CreditmemoSaveAfterProducer extends AbstractCreditmemoProducer
{

    /**
     * @inheritDoc
     */
    public function produce(CreditmemoInterface $creditmemo = null): MessageInterface
    {
        /** @var MessageInterface $message */
        $message = $this->getMessageFactory()->create();

        if ($creditmemo === null || !$this->isConditionSatisfied($this->prepareDataForEvaluation($creditmemo))) {
            $this->getStatus()
                ->setCode(StatusInterface::SKIPPED)
                ->setOutputData($creditmemo === null ? 'Creditmemo was null' : 'Condition was not satisfied');
            return $message;
        }

        $parameters = $this->getConfiguration()->getParameters();

        if ($creditmemo !== null && $parameters->hasData(self::PAYLOAD_KEY)) {
            $template = $parameters->getData(self::PAYLOAD_KEY);
            $this->messageFiller->fill($message, $this->getDataForFiller($creditmemo), $template);
        }

        $message->getPayload()->addData([
            ObjectTypeFromMessage::OBJECT_TYPE_PATH => $this->getObjectTypeDescriptor()->getTypeCode(),
            ObjectTypeFromMessage::OBJECT_ID_PATH => $creditmemo->getEntityId()
        ]);

        $this->getStatus()->setCode(StatusInterface::SUCCESS);

        return $message;
    }

    /**
     * @param CreditmemoInterface $creditmemo
     * @return DataObject
     */
    protected function prepareDataForEvaluation(CreditmemoInterface $creditmemo = null): DataObject
    {
        /** @var DataObject $dataToEvaluate */
        $dataToEvaluate = $this->dataObjectFactory->create();

        if ($creditmemo === null) {
            return $dataToEvaluate;
        }

        $dataToEvaluate->setData('data', $creditmemo);
        $dataToEvaluate->setData('origdata', $creditmemo->getOrigData() ?: $this->dataObjectFactory->create());
        return $dataToEvaluate;
    }

    /**
     * @param CreditmemoInterface $creditmemo
     * @return mixed
     */
    protected function getDataForFiller(CreditmemoInterface $creditmemo)
    {
        return $this->dataObjectFactory->create(
            [
                'data' => [
                    'data' => $creditmemo,
                    'origdata' => $creditmemo->getOrigData() ?: $this->dataObjectFactory->create()
                ]
            ]
        );
    }

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'CreditMemo Save After Producer';
    }

    /**
     * @inheritDoc
     */
    public function getUniqueName(): string
    {
        return 'FiloBlu_Esb::creditmemo_save_after';
    }
}
