<?php

namespace FiloBlu\Refilo\Observer;

use FiloBlu\Refilo\Helper\OrderCustomer;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Model\Order\OrderCustomerDelegate;
use Magento\Sales\Model\ResourceModel\Order\Collection;
use Magento\Sales\Model\Order\CustomerAssignment;

class CustomerRegisterSuccessObserver implements ObserverInterface
{
    /**
     * @var Collection
     */
    protected $orderCollection;
    /**
     * @var CustomerAssignment
     */
    protected $assignmentService;
    /**
     * @var CustomerRepositoryInterface
     */
    private $customerRepository;
    /**
     * @var OrderCustomer
     */
    private $orderCustomerHelper;

    /**
     * @param Collection $orderCollection
     * @param CustomerAssignment $assignmentService
     * @param CustomerRepositoryInterface $customerRepository
     * @param OrderCustomer $orderCustomerHelper
     */
    public function __construct(
        Collection $orderCollection,
        CustomerAssignment $assignmentService,
        CustomerRepositoryInterface $customerRepository,
        OrderCustomer $orderCustomerHelper
    )
    {
        $this->orderCollection = $orderCollection;
        $this->assignmentService = $assignmentService;
        $this->customerRepository = $customerRepository;
        $this->orderCustomerHelper = $orderCustomerHelper;
    }

    /**
     * @param Observer $observer
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function execute(Observer $observer)
    {
        if (!$this->orderCustomerHelper->isOrderSelectionStrategyEnabled()) {
            return;
        }

        $customer = $this->customerRepository->get($observer->getEvent()->getCustomer()->getEmail()) ;
        $orders = $this->getCustomerOrders($customer->getEmail(), $customer->getCreatedAt());

        if (!$orders) {
            return;
        }

        /** @var \Magento\Sales\Model\Order $order */
        foreach ($orders as $order) {
            $this->assignmentService->execute($order, $customer);
        }
    }

    /**
     * @param $customerEmailId
     * @param $customerCreatedAt
     * @return \Magento\Framework\DataObject[]
     */
    public function getCustomerOrders($customerEmailId, $customerCreatedAt)
    {
        $customerOrders = $this->orderCollection
            ->addAttributeToFilter('customer_email', $customerEmailId)
            ->addAttributeToFilter('customer_id', ['null' => true]);

        if ($filter = $this->orderCustomerHelper->getOrderStrategyFilter($customerCreatedAt)) {
            $customerOrders->addAttributeToFilter(
                'created_at', $filter
            );
        }

        return $customerOrders->getItems();
    }
}
