<?php
/**
 * Module-owned destructive uninstall plan.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Extension;

use ScheduledChanges\Database\TableNames;

/**
 * Builds a deterministic cleanup plan from module manifests.
 */
final class ModuleUninstallPlan {
	private ModuleResourceSelector $resources;
	private TableNames $tables;

	public function __construct( ?ModuleResourceSelector $resources = null, ?TableNames $tables = null ) {
		$this->resources = $resources ?? new ModuleResourceSelector();
		$this->tables    = $tables ?? new TableNames();
	}

	/** @return string[] */
	public function options(): array {
		return $this->resources->resources( ModuleDefinition::RESOURCE_OPTION, true );
	}

	/** @return string[] */
	public function metaKeys(): array {
		return $this->resources->resources( ModuleDefinition::RESOURCE_META, true );
	}

	/** @return string[] */
	public function actionHooks(): array {
		return $this->resources->resources( ModuleDefinition::RESOURCE_ACTION_HOOK, true );
	}

	/** @return string[] */
	public function cleanupOperations(): array {
		return $this->resources->resources( ModuleDefinition::RESOURCE_UNINSTALL, true );
	}

	/**
	 * Returns concrete table names in dependent-first uninstall order.
	 *
	 * @return string[]
	 */
	public function tables(): array {
		$available = $this->tables->all();
		$selected  = array();

		foreach ( $this->resources->resources( ModuleDefinition::RESOURCE_TABLE, true ) as $table_key ) {
			if ( isset( $available[ $table_key ] ) ) {
				$selected[] = $available[ $table_key ];
			}
		}

		return $selected;
	}
}
