<?php
/**
 * Post install migration for version 3.2.0 of the plugin.
 *
 * @package    SeQura/WC
 * @subpackage SeQura/WC/Repositories
 */

namespace SeQura\WC\Repositories\Migrations;

use Exception;
use Throwable;
use SeQura\WC\Repositories\Interface_Cache_Repository;
use SeQura\WC\Repositories\Repository;

/**
 * Post install migration for version 3.2.0 of the plugin.
 */
class Migration_Install_320 extends Migration {

	/**
	 * Hook name.
	 * 
	 * @var string
	 */
	private $hook_name;

	/**
	 * Entity repository.
	 * 
	 * @var Repository
	 */
	private $entity_repository;

	/**
	 * Queue repository.
	 * 
	 * @var Repository
	 */
	private $queue_repository;

	/**
	 * Constructor
	 */
	public function __construct( 
		\wpdb $wpdb,
		Interface_Cache_Repository $cache,
		string $hook_name,
		Repository $entity_repository,
		Repository $queue_repository
	) {
		parent::__construct( $wpdb, $cache );
		$this->hook_name         = $hook_name;
		$this->entity_repository = $entity_repository;
		$this->queue_repository  = $queue_repository;
	}

	/**
	 * Get the plugin version when the changes were made.
	 */
	public function get_version(): string {
		return '3.2.0';
	}

	/**
	 * Execute the migration logic.
	 *
	 * @throws Throwable|Critical_Migration_Exception
	 */
	protected function execute(): void {
		// Schedule indexing of the sequra_order table.
		$args = array( $this->hook_name );
		if ( ! \wp_next_scheduled( $this->hook_name, $args ) ) {
			\wp_schedule_event( time(), 'hourly', $this->hook_name, $args );
		}
		// Index tables with almost no data or no data at all (sequra_entity, sequra_queue).
		$repos = array(
			$this->entity_repository,
			$this->queue_repository,
		);
		foreach ( $repos as $repo ) {
			foreach ( $repo->get_required_indexes() as $index ) {
				if ( ! $repo->add_index( $index ) ) {
					throw new Exception( 'Failed to add index ' . \sanitize_key( $index->name ) . ' to table ' . \sanitize_key( $repo->get_table_name() ) );
				}
			}
		}
	}
}
