<?php
declare(strict_types=1);

namespace Autogedal\Extend\Cron;

use Autogedal\Extend\Model\Product\SpecsDescriptionManager;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Model\Product\Action as ProductAction;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;

class UpdateSpecsDescription
{
    private const TARGET_CATEGORY_ID = 59;
    private const SPECS_MARKER = 'autogedal-specs-wrapper';

    public function __construct(
        private readonly SpecsDescriptionManager $specsManager,
        private readonly CollectionFactory $productCollectionFactory,
        private readonly ProductAction $productAction,
        private readonly LoggerInterface $logger,
        private readonly State $appState
    ) {}


    public function execute(): void
    {
        try {
            $this->appState->emulateAreaCode(
                Area::AREA_ADMINHTML,
                [$this, 'processProducts']
            );
        } catch (\Exception $e) {
            $this->logger->error('Error in Autogedal Specs Description Update Cron: ' . $e->getMessage());
        }
    }


    public function processProducts(): void
    {
        $this->logger->info('Starting Autogedal Specs Description Update Cron');
        
        $storeId = 0;
        $batchSize = 500;
        $updatedCount = 0;

        $lightCollection = $this->productCollectionFactory->create();
        $lightCollection->addCategoriesFilter(['eq' => self::TARGET_CATEGORY_ID]);
        $lightCollection->addAttributeToSelect('description');

        $productIdsToProcess = [];

        foreach ($lightCollection as $product) {
            $description = (string)$product->getData('description');
            
            if (!str_contains($description, self::SPECS_MARKER)) {
                $productIdsToProcess[] = $product->getId();
            }
        }
        
        $lightCollection->clear();

        if (empty($productIdsToProcess)) {
            $this->logger->info('No products need specs update in category ' . self::TARGET_CATEGORY_ID);
            return;
        }

        $this->logger->info(sprintf('Found %d products that need specs update. Processing in batches...', count($productIdsToProcess)));

        $batches = array_chunk($productIdsToProcess, $batchSize);

        foreach ($batches as $batchIds) {
            $collection = $this->productCollectionFactory->create();
            $collection->addAttributeToSelect('*');
            $collection->addIdFilter($batchIds);

            foreach ($collection as $product) {
                $product->setStoreId($storeId);

                $wasModified = $this->specsManager->updateDescription($product);
                
                if ($wasModified) {
                    $this->productAction->updateAttributes(
                        [$product->getId()],
                        ['description' => $product->getData('description')],
                        $storeId
                    );
                    $updatedCount++;
                }
            }

            $collection->clear();
        }

        $this->logger->info(sprintf('Autogedal Specs Description Update Cron finished. Updated %d products.', $updatedCount));
    }
}
