<?php

namespace CelerSearch;

use CelerSearch\Admin\Boot as AdminBoot;
use CelerSearch\Autocomplete\Boot as AutocompleteBoot;
use CelerSearch\Database\Setup;
use CelerSearch\Factories\AdminFactory;
use CelerSearch\Factories\ManagerFactory;
use CelerSearch\Factories\ObserverFactory;
use CelerSearch\Integrations\WooCommerce\ShopFilterRestApi;
use CelerSearch\Integrations\WooCommerce\ShopFilters;
use CelerSearch\Interfaces\IRegistrable;
use CelerSearch\Queue\Queue;
use CelerSearch\Search\OrderQueryIntegration;
use CelerSearch\Search\QueryIntegration;
use CelerSearch\Search\SearchPageOverride;
use CelerSearch\Blocks\Boot as BlocksBoot;
use CelerSearch\Shortcodes\Boot as ShortcodesBoot;
use CelerSearch\Views\RestApi as ViewsRestApi;
use CelerSearch\Views\ViewAssets;

class Boot implements IRegistrable {

	/**
	 * The admin instance
	 * @var Admin\Boot
	 */
	public AdminBoot $admin;

	/**
	 * The manager instance
	 * @var Manager
	 */
	public Manager $manager;

	/**
	 * The cron instance
	 * @var Cron
	 */
	public Cron $cron;

	/**
	 * The query integration instance
	 * @var QueryIntegration
	 */
	public QueryIntegration $query_integration;

	/**
	 * The order query integration instance
	 * @var OrderQueryIntegration
	 */
	public OrderQueryIntegration $order_query_integration;

	/**
	 * The autocomplete instance
	 * @var AutocompleteBoot
	 */
	public AutocompleteBoot $autocomplete;

	/**
	 * Registers certain group of hooks (actions/filters)
	 *
	 * @return void
	 */
	public function register(): void {
		Setup::migrate();

		// Register queue handlers (Action Scheduler hooks)
		Queue::register_handlers();

		$this->manager                 = ManagerFactory::create();
		$this->admin                   = AdminFactory::create( $this->manager );
		$this->cron                    = new Cron();
		$this->query_integration       = new QueryIntegration();
		$this->order_query_integration = new OrderQueryIntegration();
		$this->autocomplete            = new AutocompleteBoot();

		// Register observers for real-time sync
		$this->register_observers();

		$this->cron->register();
		( new SearchPageOverride() )->register();
		$this->query_integration->register();
		$this->order_query_integration->register();
		$this->autocomplete->register();

		// Views + Shortcodes
		( new ViewAssets() )->register();
		( new ViewsRestApi() )->register();
		( new ShortcodesBoot() )->register();
		( new BlocksBoot() )->register();

		// WooCommerce shop filters (conditional on WooCommerce being active)
		if ( class_exists( 'WooCommerce' ) ) {
			( new ShopFilterRestApi() )->register();
			( new ShopFilters() )->register();
		}
	}

	/**
	 * Register observers for all active indices
	 *
	 * @return void
	 */
	private function register_observers(): void {
		$observers = ObserverFactory::create_all();

		foreach ( $observers as $observer ) {
			$this->manager->add_observer( $observer );
		}

		// Start observing for changes
		$this->manager->observe();
	}
}