<?php

namespace Easymailing\App\Core\Provider\Woocommerce\Batch;

use Easymailing\App\Api\Client;
use Easymailing\App\Api\Exception\NotFoundException;
use Easymailing\App\Core\Log\LogManager;
use Easymailing\App\Core\Provider\Woocommerce\Model\BatchOperationIdentifier;
use Easymailing\App\Core\Provider\Woocommerce\Model\LogType;
use Easymailing\App\Core\Provider\Woocommerce\Model\SynchronizationStatus;
use Easymailing\App\Core\Provider\Woocommerce\Service\MetadataHelper;
use Easymailing\App\Repository\ConfigRepository;


class CategoryBatchOperations
{

	private $configRepository;
	private $logManager;

	public function __construct(ConfigRepository $configRepository, LogManager $logManager)
	{
		$this->configRepository = $configRepository;
		$this->logManager = $logManager;
	}

    public function getCategoriesBatchOperations(): array
    {
        $batchOperations = [];
		$this->logManager->createLog(LogType::BATCH, "Start CategoryBatchOperations");

	    $config = $this->configRepository->getSynchronizationConfig();

        // Generar el URL base para las categorías
		$baseUrl = sprintf("/stores/%s/categories", $config->getShopId());

        try {
            // Obtener todas las categorías de productos de WooCommerce
            $wcProductCategories = get_terms([
                'taxonomy' => 'product_cat',
                'hide_empty' => false,
            ]);

            $retryOnly = (bool) get_option(MetadataHelper::getRetryOnlyMode());

            // Recorrer todas las categorías de WooCommerce
            foreach ($wcProductCategories as $wcProductCategory) {
                $categoryId = $wcProductCategory->term_id;

                if ($retryOnly) {
                    $status = get_term_meta($categoryId, MetadataHelper::getSynchronizationStatus(), true);
                    if ($status !== SynchronizationStatus::ERROR) {
                        continue;
                    }
                }

                // Obtener el ID de la categoría en EasyMailing
                $emCategoryId = get_term_meta($categoryId, MetadataHelper::getResourceId(), true);
                $categoryUrl = $baseUrl . '/' . ($emCategoryId ?: '');

                // Manejo del ID de categoría de EasyMailing
                if ($emCategoryId) {
					$method = 'PUT';
                } else {
                    $emCategoryId = wp_generate_uuid4();
                    $categoryUrl = $baseUrl;
                    $method = 'POST';
                }

                // Obtener el thumbnail (si existe)
                $thumbnailId = get_term_meta($categoryId, 'thumbnail_id', true);
                $imageUrl = $thumbnailId ? wp_get_attachment_image_url($thumbnailId, 'full') : null;

                // Crear el cuerpo de la petición para EasyMailing
                $body = [
                    'title' => $wcProductCategory->name,
                    'image_url' => $imageUrl,
                ];

                // Si es un POST, añadir el campo resource_id
                if ($method === 'POST') {
                    $body['resource_id'] = $emCategoryId;
                }

				update_term_meta($categoryId, MetadataHelper::getResourceId(), $emCategoryId);

                // Agregar la operación al batch
                $batchOperations[] = [
                    'method' => $method,
                    'path' => $categoryUrl,
                    'body' => json_encode($body),
                    "external_identifier" => BatchOperationIdentifier::buildIdentifier(BatchOperationIdentifier::CATEGORY, $categoryId)
                ];
            }
        } catch (\Exception $e) {
            // Manejar cualquier otra excepción
			$this->logManager->createLog(LogType::BATCH, sprintf("Error in CategoryBatchOperations: %s", $e->getMessage()));
        }

        $this->logManager->createLog(LogType::BATCH, "End CategoryBatchOperations");
        return $batchOperations;
    }


}
