<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */
declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Observer\Catalog;

use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
use WriteTextAI\WriteTextAI\Model\NewRecordsManager;
use WriteTextAI\WriteTextAI\Model\HandleKeywordOptimization;
use WriteTextAI\WriteTextAI\Model\ArchiveManager;

class ProductDeleteAfter implements ObserverInterface
{
    /**
     * @var NewRecordsManager
     */
    protected $newRecordsManager;

    /**
     * @var HandleKeywordOptimization
     */
    protected $handleKeywordOptimization;

    /**
     * @var ArchiveManager
     */
    protected $archiveManager;

    /**
     * Constructor
     *
     * @param NewRecordsManager $newRecordsManager
     * @param HandleKeywordOptimization $handleKeywordOptimization
     * @param ArchiveManager $archiveManager
     */
    public function __construct(
        NewRecordsManager $newRecordsManager,
        HandleKeywordOptimization $handleKeywordOptimization,
        ArchiveManager $archiveManager
    ) {
        $this->newRecordsManager = $newRecordsManager;
        $this->handleKeywordOptimization = $handleKeywordOptimization;
        $this->archiveManager = $archiveManager;
    }

    /**
     * Execute observer
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        try {
            $product = $observer->getEvent()->getProduct();
            $productId = $product->getId();
            $this->newRecordsManager->deleteRecord($productId, 'Product');
            $this->archiveManager->archiveRecord((string)$productId, 'Product');
            $handlingStatus = $this->handleKeywordOptimization->deleteKeywordOptimizations([$productId], 'Product');
        } catch (\Exception $e) {
            // Do nothing
            true; // suppresses empty catch warning
        }
    }
}
