<?php
$_db_migration_to = '11.01'; // 1.10.0
if (!isset($migrations) || !is_object($migrations))
	die("This file cannot be executed directly");
$migrations->CheckValid($_db_migration_to);
//===========================================================================================



$migrations->Run('2021-04-19_reindex_pages.php', <<<'DB_UPDATE_FILE'
<?php
use Claromentis\Core\Services;
use Claromentis\Pages;
use Claromentis\Search;
use Claromentis\Setup\SetupFacade;

/**
 * claromentis/product/pages!52 BT-2366 Implemented search indexing for page permissions
 *
 * This migration goes against our recommendation of only using services from `SetupFacade` in order to avoid deployment
 * complexity. If it didn't, remapping and reindexing of Pages search documents would need to be invoked manually via
 * the web interface or CLC commands for every system upgraded to this version of Pages.
 *
 * Let this migration serve as an example approach to remapping and reindexing Elasticsearch documents until it's
 * formally supported via our migrations facade (FRAM-456).
 *
 * @var SetupFacade $migrations
 */
$migrations->Log('Remapping Page URLs to Elasticsearch and queuing them for reindexing');

$core = Services::I()->container;

/**
 * @var Search\Indexing\Client\ClientInterface $indexer
 * @var Search\Indexing\Reindexer              $reindexer
 * @var Search\ItemTypeFactory                 $factory
 */
$indexer   = $core['search.indexer'];
$reindexer = $core['search.reindexer'];
$factory   = $core['search.item_type_factory'];

// No try-catch here, a remapping failure is fatal and we want it to halt an upgrade and retry on next upgrade
$item = $factory->GetIndexingObject(Pages\Search\Indexing\PageIndexing::TYPE_NAME);
$item->InitMapping($indexer);

try {
	$reindexer->Reindex(Pages\Search\Indexing\PageIndexing::TYPE_NAME);
} catch (Exception $exception) {
	$migrations->Log($exception);
	$migrations->Log("Error while queuing Page URLs for reindexing: {$exception->getMessage()}");
	$migrations->Log("Please try reindexing Pages URLs from the Search Admin panel or get in contact with developers");
	$migrations->Log("This error is not fatal, so migrations will continue");
}

DB_UPDATE_FILE
);


//===========================================================================================
$migrations->SetVersion('11.01');
