<?php

namespace Magetop\Agency\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magetop\Agency\Model\ResourceModel\Items\CollectionFactory as ItemsCollection;

class DeleteProduct implements ObserverInterface
{
    /**
     * @var ItemsCollection
     */
    protected $_itemsCollection;

    /**
     * @param ItemsCollection $itemsCollectionFactory
     */
    public function __construct(ItemsCollection $itemsCollectionFactory)
    {
        $this->_itemsCollection = $itemsCollectionFactory;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        try {
            $productId = $observer->getProduct()->getId();
            $collection = $this->_itemsCollection
                                ->create()
                                ->addFieldToFilter('product_id', $productId);
            foreach ($collection as $item) {
                $item->delete();
            }
        } catch(\Exception $e) {
            $this->messageManager->add($e->getMessage());
        }
    }
}