<?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\InvoiceInterface;

/**
 * Class InvoiceSaveAfter
 * @package FiloBlu\Esb\Model\Producer
 */
class InvoiceSaveAfterProducer extends AbstractInvoiceProducer
{

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

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

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

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

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

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

        return $message;
    }

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

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

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

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

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

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