<?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 ) ) {
			error_log( "[FacetWP Sync] Skipping batch {$item['batch']}: previous failure detected." );

			return false;
		}

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

		if ( ( ! $result || is_wp_error( $result) ) && $item['tries']++ < 3 ) {
			$error_message = is_wp_error( $result ) ? $result->get_error_message() : 'Unknown error';

			error_log( "[FacetWP Sync] Retry {$item['tries']}/3 for batch {$item['batch']} due to error: {$error_message}" );

			sleep(5);

			return $item;
		}

		if ( ! $result || is_wp_error( $result) ) {
			update_option( self::FAILURE_FLAG_OPTION_KEY, true );

			$error_message = is_wp_error( $result ) ? $result->get_error_message() : 'Unknown error';

			error_log( "[FacetWP Sync] Batch {$item['batch']} failed after 3 retries. Aborting. Error: {$error_message}" );
		}

		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();
		}

		// Clear cache
		$result = Facet_Wp_Remote_Data_Cache::delete_cache();

		if ( is_wp_error( $result ) ) {
			error_log( '[FacetWP Sync] Sync completed but clearing cache failed. Error: ' . $result->get_error_message() );
		}
	}

}