<?php
declare( strict_types=1 );

namespace FiboFilters\API;

use FiboFilters\Config\Index as ConfigIndex;
use FiboFilters\Indexer\BuilderUI;
use FiboFilters\Indexer\BuildInfo;
use FiboFilters\Indexer\Config;
use WP_REST_Response;

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

/**
 * Class Indexer
 */
class Index {
	/** @var BuilderUI */
	private $builder_ui;

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

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

	/** @var ConfigIndex */
	private $index;

	public function __construct( BuilderUI $builder_ui, BuildInfo $build_info, Config $config, ConfigIndex $index ) {
		$this->builder_ui = $builder_ui;
		$this->build_info = $build_info;
		$this->config     = $config;
		$this->index      = $index;
	}

	public function build(): WP_REST_Response {
		$this->index->build();
		$data = $this->builder_ui->get_status_data();

		return new WP_REST_Response( $data );
	}

	public function cancel(): WP_REST_Response {
		if ( $this->build_info->get_info( 'status', $this->config->get_index_role() ) !== 'completed' ) {
			$this->index->cancel();
		}
		$data = $this->builder_ui->get_status_data();

		return new WP_REST_Response( $data );
	}

	public function status(): WP_REST_Response {
		$this->index->check_if_indexer_is_working_too_long();

		$data = $this->builder_ui->get_status_data();

		return new WP_REST_Response( $data );
	}
}
