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

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

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

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

    /**
     * Execute observer
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {

        try {
            $adapter = $observer->getEvent()->getAdapter();
            $bunch = $observer->getEvent()->getBunch();
            $toDeleteKOIds = [];
            if (!empty($bunch)) {
                foreach ($bunch as $rowNum => $rowData) {
                    if (isset($rowData['sku'])) {
                        $sku = $rowData['sku'];
                        // Get the product ID from the old SKU data
                        $oldSku = $adapter->getOldSku();
                        if (isset($oldSku[strtolower($sku)]['entity_id'])) {
                            $productId = $oldSku[strtolower($sku)]['entity_id'];
                            $this->newRecordsManager->deleteRecord($productId, 'Product');
                            $this->archiveManager->archiveRecord((string)$productId, 'Product');
                            $toDeleteKOIds[] = $productId;
                        }
                    }
                }
            }
            if (!empty($toDeleteKOIds)) {
                $handlingStatus = $this->handleKeywordOptimization
                    ->deleteKeywordOptimizations($toDeleteKOIds, 'Product');
            }
        } catch (\Exception $e) {
            // Do nothing
            true; // suppresses empty catch warning
        }
    }
}
