<?php
/**
 * Module distribution profile resolver.
 *
 * @package ScheduledChanges
 */

namespace ScheduledChanges\Extension;

/**
 * Resolves profile-selected modules without user-facing toggles.
 */
final class ModuleProfileResolver {
	public const PROFILE_FULL    = 'full';
	public const PROFILE_LITE    = 'lite';
	public const PROFILE_MINIMAL = 'minimal';

	private const PROFILES = array(
		self::PROFILE_FULL,
		self::PROFILE_LITE,
		self::PROFILE_MINIMAL,
	);

	/**
	 * Returns the active distribution profile.
	 */
	public function currentProfile(): string {
		if ( defined( 'SCHEDULED_CHANGES_PACKAGED_MODULE_PROFILE' ) ) {
			$profile = (string) SCHEDULED_CHANGES_PACKAGED_MODULE_PROFILE;
		} else {
			$profile = defined( 'SCHEDULED_CHANGES_MODULE_PROFILE' ) ? (string) SCHEDULED_CHANGES_MODULE_PROFILE : self::PROFILE_FULL;
		}
		$profile = PublicHooks::moduleDistributionProfile( $profile );

		return $this->normalizeProfile( $profile );
	}

	/**
	 * Returns true when a module should be included by a profile.
	 */
	public function includes( ModuleDefinition $definition, string $profile ): bool {
		$profile = $this->normalizeProfile( $profile );

		if ( self::PROFILE_FULL === $profile ) {
			return true;
		}

		if ( self::PROFILE_MINIMAL === $profile ) {
			return in_array(
				$definition->slug(),
				array(
					'scheduled-changes-provider-discovery',
					'scheduled-changes-validation',
					'scheduled-changes-audit-diagnostics',
				),
				true
			);
		}

		return ModuleDefinition::VISIBILITY_DEVELOPMENT !== $definition->visibility()
			&& ModuleDefinition::VISIBILITY_HIDDEN !== $definition->visibility();
	}

	/**
	 * Returns true when an included module should be displayed on the Modules page.
	 */
	public function visible( ModuleDefinition $definition, string $profile ): bool {
		$profile = $this->normalizeProfile( $profile );

		if ( ! $this->includes( $definition, $profile ) ) {
			return false;
		}

		if ( self::PROFILE_FULL === $profile ) {
			return true;
		}

		return ModuleDefinition::VISIBILITY_PUBLIC === $definition->visibility()
			|| ModuleDefinition::VISIBILITY_GROUPED_PUBLIC === $definition->visibility();
	}

	public function normalizeProfile( string $profile ): string {
		$profile = trim( strtolower( $profile ) );

		return in_array( $profile, self::PROFILES, true ) ? $profile : self::PROFILE_FULL;
	}
}
