<?php
/**
 * Provides automatically identified tracker configuration.
 *
 * Searches for available trackers and automatically configures them.
 *
 * @package Ealab\Deployer
 */

namespace EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\TrackerConfig;

use EaLab\WP_Deployer\vendor\Ealab\Deployer\Tracking\Config\ConfigProviderBase;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\Database;
use EaLab\WP_Deployer\vendor\Ealab\Deployer\Utility\TrackerConfigUtils;

/**
 * Provides automatically identified tracker configuration.
 *
 * Searches for available trackers and automatically configures them.
 */
class AutomaticTrackerConfigProvider extends ConfigProviderBase {
	/**
	 * {@inheritDoc}
	 */
	public function collect(): ?array {
		// Read the database structure.
		$table_names = Database::getTableNames( array( 'without_dsc_tables' => true ) );

		$config = array();

		// Remove the table prefixes to get the tracker IDs.
		$tracker_ids = array_map(
			function ( $table_name ) {
				return Database::removeDatabasePrefix( $table_name );
			},
			$table_names
		);

		$table_names = array_combine( $tracker_ids, $table_names );

		foreach ( $table_names as $tracker_id => $table_name ) {
			$definition = Database::getPrimaryKeysColumnsDefinition( $table_name );

			if ( 1 !== count( $definition ) ) {
				// We only support single primary key tables.
				continue;
			}

			if ( 'auto_increment' !== $definition[0]['EXTRA'] ) {
				// We only support auto increment primary keys.
				continue;
			}

			$config[ $tracker_id ] = array(
				'field_definitions_overrides' => array(),
				'local_id_field'              => array(
					'name' => $definition[0]['COLUMN_NAME'],
					'type' => $definition[0]['COLUMN_TYPE'],
				),
				'plugin'                      => TrackerConfigUtils::findTrackerPlugin( $tracker_id ) ?? '',
				'tracker_id'                  => $tracker_id,
			);
		}

		$this->config = $config;

		return $this->config;
	}
}
