<?php

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

use Easymailing\App\Core\Provider\Woocommerce\Model\SynchronizationStatus;

class FailedSynchronizationCleaner
{
	public function dismissFailedItems(): int
	{
		$total = 0;

		$total += $this->clearUserErrors();
		$total += $this->clearPostErrors();
		$total += $this->clearTermErrors();

		delete_option(MetadataHelper::getRetryOnlyMode());

		return $total;
	}

	private function clearUserErrors(): int
	{
		$ids = $this->getFailedIds('usermeta', 'user_id');
		foreach ($ids as $id) {
			delete_user_meta($id, MetadataHelper::getSynchronizationStatus());
			delete_user_meta($id, MetadataHelper::getErrorMessage());
		}

		return count($ids);
	}

	private function clearPostErrors(): int
	{
		$ids = $this->getFailedIds('postmeta', 'post_id');
		foreach ($ids as $id) {
			delete_post_meta($id, MetadataHelper::getSynchronizationStatus());
			delete_post_meta($id, MetadataHelper::getErrorMessage());
		}

		return count($ids);
	}

	private function clearTermErrors(): int
	{
		$ids = $this->getFailedIds('termmeta', 'term_id');
		foreach ($ids as $id) {
			delete_term_meta($id, MetadataHelper::getSynchronizationStatus());
			delete_term_meta($id, MetadataHelper::getErrorMessage());
		}

		return count($ids);
	}

	private function getFailedIds(string $tableProperty, string $idColumn): array
	{
		global $wpdb;

		$table = $wpdb->{$tableProperty};
		$ids = $wpdb->get_col($wpdb->prepare(
			"SELECT DISTINCT {$idColumn} FROM {$table} WHERE meta_key = %s AND meta_value = %s",
			MetadataHelper::getSynchronizationStatus(),
			SynchronizationStatus::ERROR
		));

		return array_map('intval', is_array($ids) ? $ids : []);
	}
}
