<?php
declare( strict_types=1 );

namespace FiboFilters\Indexer;

use FiboFilters\Indexer\BackgroundProcessing\AsyncRequestWithCron;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class AsyncRebuildIndex
 */
class AsyncRebuildIndex extends AsyncRequestWithCron {
	/**
	 * Prefix
	 *
	 * @var string
	 */
	protected $prefix = 'fibofilters';

	/**
	 * @var string
	 */
	protected $action = 'async_rebuild_index';

	/**
	 * @var string
	 */
	protected $name = '[Indexer]';

	/** @var Builder */
	protected $builder;

	/** @var BuildInfo */
	protected $build_info;

	/** @var Config */
	protected $config;

	public function __construct( Builder $builder, BuildInfo $build_info, Config $config, Logger $logger ) {
		$this->builder    = $builder;
		$this->build_info = $build_info;
		$this->config     = $config;
		$this->logger     = $logger;

		parent::__construct( $this->logger );
	}

	/**
	 * Handle
	 */
	protected function handle(): void {
		if ( $this->build_info->get_info( 'status', $this->config->get_index_role() ) === 'completed' || isset( $this->data['force'] ) ) {
			$this->builder->build_index_process();
		}
	}

	/**
	 * Handle cron healthcheck
	 */
	public function handle_cron_healthcheck(): void {
		$this->logger->log( $this->name . ' Handle async request via cron healthcheck', 'debug', 'file', 'bg-process' );

		// The data is not stored in the database, so we have to pass it in again in cron.
		$this->data( [ 'force' => true ] );

		$this->handle();

		exit;
	}
}
