<?php
// DESCRIPTION: Registers the Action Scheduler hook for backfill batch processing,
// orchestrating batch execution, progress updates, and next-batch scheduling.

namespace SheetWise\Backfill;

class ScheduledHooks {

	/**
	 * Register the backfill batch action
	 *
	 * @since 2.0.0
	 */
	public function __construct() {
		add_action( 'sheetwise_backfill_batch', [ $this, 'process_batch' ] );
	}

	/**
	 * Process a single backfill batch
	 *
	 * Called by Action Scheduler. Processes one batch of records,
	 * updates progress, and schedules the next batch if needed.
	 *
	 * @since 2.0.0
	 *
	 * @param array $args { integration_id, offset }
	 *
	 * @return void
	 */
	public function process_batch( $args ) {
		if ( empty( $args['integration_id'] ) || ! isset( $args['offset'] ) ) {
			return;
		}

		$integration_id = absint( $args['integration_id'] );
		$offset         = absint( $args['offset'] );

		$manager = new BackfillManager();
		$status  = $manager->get_status( $integration_id );

		// Bail if cancelled or no active job
		if ( ! $status || $status['status'] === 'cancelled' ) {
			return;
		}

		$processor = new BackfillProcessor();

		try {
			$processed_count = $processor->process_batch( $integration_id, $offset );
			$new_processed   = $offset + $processed_count;

			$manager->update_progress( $integration_id, $new_processed );

			if ( $processed_count > 0 && $new_processed < $status['total'] ) {
				$processor->schedule_next_batch( $integration_id, $new_processed );
			} else {
				$manager->complete( $integration_id );
			}
		} catch ( \Exception $e ) {
			$manager->fail( $integration_id, $e->getMessage() );
		}
	}
}
