<?php

class Facet_Wp_Remote_Data_Background_Process extends WP_Background_Process {

	protected $prefix = 'sw';

	protected $action = 'facet_remote_data_index_table_sync';

	const FAILURE_FLAG_OPTION_KEY = 'facetwp_index_table_sync_failed';

	protected function task( $item ) {
		// Stop if previous failure is recorded
		if ( get_option( self::FAILURE_FLAG_OPTION_KEY ) ) {
			return false;
		}

		$result = Facet_Wp_Remote_Data_Admin::sync_index_batch( $item['batch'] );

		if ( ( ! $result || is_wp_error( $result) ) && $item['tries']++ < 3 ) {
			sleep(5);

			return $item;
		}

		if ( ! $result || is_wp_error( $result) ) {
			update_option( self::FAILURE_FLAG_OPTION_KEY, true );
			error_log( "[FacetWP Sync] Batch {$item['batch']} failed after 3 retries. Aborting." );
		}

		return false;
	}

	protected function complete() {
		parent::complete();

		$has_failed = get_option( self::FAILURE_FLAG_OPTION_KEY );

		// Clean up flag either way
		delete_option( self::FAILURE_FLAG_OPTION_KEY );

		if ( $has_failed ) {
			error_log( '[FacetWP Sync] Sync aborted due to failure. Restarting from batch 1...' );

			Facet_Wp_Remote_Data_Admin::sync_facetwp_index_table();
		}
	}

}