<?php

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

use Easymailing\App\Api\Client;
use Easymailing\App\Core\Log\LogManager;
use Easymailing\App\Core\Provider\Woocommerce\Model\LogType;

class BatchEnqueueManager
{

	const SYNCHRONIZATION_BACKGROUND_TASK = 'em_background_task';
	const SYNCHRONIZATION_CHECK_BACKGROUND_TASK = 'em_check_background_task';

	const ENQUEUE_GROUP = 'easymailing_plugin';

	private $logManager;
	private $apiClient;

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

	public function enqueue(?bool $retryOnly = null): void
	{
		// null → no tocar el flag (llamada desde advanceToNextPhase entre fases,
		// debe preservar el retry_only_mode activo de la sync actual).
		// true → setear (retry manual).
		// false → borrar (sync "full" iniciada por el usuario).
		if ($retryOnly === true) {
			update_option(MetadataHelper::getRetryOnlyMode(), true);
		} elseif ($retryOnly === false) {
			delete_option(MetadataHelper::getRetryOnlyMode());
		}

		$actionID = as_enqueue_async_action(self::SYNCHRONIZATION_BACKGROUND_TASK, [], self::ENQUEUE_GROUP, true, 5);

		if ($actionID) {
			$currentRetryOnly = (bool) get_option(MetadataHelper::getRetryOnlyMode()) ? 'true' : 'false';
			$this->logManager->createLog(LogType::BATCH, sprintf("Batch Enqueue SYNCHRONIZATION success with ID: %s (retry_only=%s)", $actionID, $currentRetryOnly));
			update_option(MetadataHelper::getBackgroundTaskId(), $actionID);
		}
		else{
			$this->logManager->createLog(LogType::BATCH, "Batch Enqueue SYNCHRONIZATION failed");
		}
	}

	public function enqueueCheckBackgroundTask(): void
	{
		// El API suele terminar un batch en segundos. Con 10s de retraso el plugin
		// reacciona rápido sin saturar (Action Scheduler sigue encargado de ejecutarla
		// asíncronamente; no bloquea la request del usuario).
		$scheduledTime = time() + 10;

		$actionID = as_schedule_single_action($scheduledTime, self::SYNCHRONIZATION_CHECK_BACKGROUND_TASK, [], self::ENQUEUE_GROUP);

		if ($actionID) {
			$this->logManager->createLog(LogType::BATCH, sprintf("Batch Enqueue CHECK SYNCHRONIZATION success with ID: %s", $actionID));
			update_option(MetadataHelper::getCheckBackgroundTaskId(), $actionID);
		} else {
			$this->logManager->createLog(LogType::BATCH, "Batch Enqueue CHECK SYNCHRONIZATION failed");
		}
	}

	public function cancelScheduledActions(): void
	{
		as_unschedule_all_actions(self::SYNCHRONIZATION_BACKGROUND_TASK, [], self::ENQUEUE_GROUP);
		as_unschedule_all_actions(self::SYNCHRONIZATION_CHECK_BACKGROUND_TASK, [], self::ENQUEUE_GROUP);
		update_option(MetadataHelper::getBackgroundTaskId(), null);
		update_option(MetadataHelper::getBatchSynchronizationPhase(), null);
		update_option(MetadataHelper::getBatchSynchronizationProgress(), null);
		delete_option(MetadataHelper::getRetryOnlyMode());

		$iris = get_option(MetadataHelper::getApiBatchOperationsIris());

		if(!$iris){
			return;
		}

		$array = json_decode($iris, true);

		foreach($array as $iri){
			try {
				$this->apiClient->deleteBatchOperation($iri);
			}catch(\Exception $e){
				$this->logManager->createLog(LogType::BATCH, sprintf("Error in deleteBatchOperation: %s", $e->getMessage()));
			}

		}
		update_option(MetadataHelper::getApiBatchOperationsIris(), null);

	}

	public function getScheduledActions(): array
	{
		return as_get_scheduled_actions([
			'group' => self::ENQUEUE_GROUP
		]);
	}
}
