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

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

    /**
     * ProductImportBunchSaveAfter constructor.
     *
     * @param NewRecordsManager $newRecordsManager
     */
    public function __construct(
        NewRecordsManager $newRecordsManager
    ) {
        $this->newRecordsManager = $newRecordsManager;
    }

    /**
     * Execute observer
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        try {
            $adapter = $observer->getEvent()->getAdapter();
            $bunch = $observer->getEvent()->getBunch();
            
            // Get new SKUs from the adapter
            $newSkus = $adapter->getNewSku();
            
            if (!empty($newSkus)) {
                foreach ($newSkus as $sku => $skuData) {
                    // Check if this is a new product (has entity_id)
                    if (isset($skuData['entity_id']) && $skuData['entity_id']) {
                        $productId = $skuData['entity_id'];
                        $this->newRecordsManager->saveNewRecords($productId, 'Product', $sku);
                    }
                }
            }
        } catch (\Exception $e) {
            // Do nothing
            true; // suppresses empty catch warning
        }
    }
}
