<?php
/**
 * Module dependency status.
 *
 * @package ScheduledChangesWooCommerce
 */

namespace ScheduledChangesWooCommerce;

use ScheduledChanges\Extension\ModuleDefinition;
use ScheduledChanges\Extension\ExtensionDefinition;

/**
 * Evaluates core and WooCommerce compatibility for the extension scaffold.
 */
final class DependencyStatus {
	/**
	 * Returns the current dependency state.
	 *
	 * @return array{loadable:bool,lifecycle_status:string,message:string,verified_lifecycle:string[],certification:array<string,mixed>}
	 */
	public static function current(): array {
		if ( ! class_exists( ModuleDefinition::class ) || ! class_exists( ExtensionDefinition::class ) || ! defined( 'SCHEDULED_CHANGES_VERSION' ) ) {
			return self::failure(
				'missing',
				'Scheduled Changes core is required before Scheduled Changes for WooCommerce can load.'
			);
		}

		if ( version_compare( (string) SCHEDULED_CHANGES_VERSION, (string) SCHEDULED_CHANGES_WC_MIN_CORE_VERSION, '<' ) ) {
			return self::failure(
				ModuleDefinition::LIFECYCLE_INCOMPATIBLE,
				sprintf(
					'Scheduled Changes %s or newer is required before Scheduled Changes for WooCommerce can load.',
					SCHEDULED_CHANGES_WC_MIN_CORE_VERSION
				)
			);
		}

		if ( ! defined( 'WC_VERSION' ) ) {
			return self::failure(
				ModuleDefinition::LIFECYCLE_INCOMPATIBLE,
				'WooCommerce is required before the WooCommerce provider module can load.'
			);
		}

		if ( version_compare( (string) WC_VERSION, (string) SCHEDULED_CHANGES_WC_MIN_WOOCOMMERCE_VERSION, '<' ) ) {
			return self::failure(
				ModuleDefinition::LIFECYCLE_INCOMPATIBLE,
				sprintf(
					'WooCommerce %s or newer is required before the WooCommerce provider module can load.',
					SCHEDULED_CHANGES_WC_MIN_WOOCOMMERCE_VERSION
				)
			);
		}

		return array(
			'loadable'           => true,
			'lifecycle_status'   => CertificationManifest::status(),
			'message'            => CertificationManifest::message(),
			'verified_lifecycle' => CertificationManifest::verifiedLifecycle(),
			'certification'      => CertificationManifest::certification(),
		);
	}

	/**
	 * Builds a failed dependency status.
	 *
	 * @param string $status Lifecycle status.
	 * @param string $message Diagnostic message.
	 * @return array{loadable:bool,lifecycle_status:string,message:string,verified_lifecycle:string[],certification:array<string,mixed>}
	 */
	private static function failure( string $status, string $message ): array {
		return array(
			'loadable'           => false,
			'lifecycle_status'   => $status,
			'message'            => $message,
			'verified_lifecycle' => array(),
			'certification'      => array(
				'required' => true,
			),
		);
	}
}
