<?php
/**
 * Which social auth modules are enabled (reads OptionStore enabled_modules / wpps settings).
 *
 * @package WP_PowerSuite\OAuth
 */

namespace WP_PowerSuite\OAuth;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class ModuleLoader {

	public const SOCIAL_MODULE_IDS = [
		'google-sign-in',
		'facebook-sign-in',
		'github-sign-in',
	];

	public static function isModuleEnabled( string $module_id ): bool {
		return OptionStoreModuleSettingsRepository::isModuleEnabled( $module_id );
	}

	/**
	 * @return list<string>
	 */
	public static function getEnabledSocialModules(): array {
		$out = [];
		foreach ( self::SOCIAL_MODULE_IDS as $id ) {
			if ( OptionStoreModuleSettingsRepository::isModuleEnabled( $id ) ) {
				$out[] = $id;
			}
		}
		return $out;
	}

	public static function anySocialEnabled(): bool {
		return self::getEnabledSocialModules() !== [];
	}

	/**
	 * Enabled in PowerSuite and OAuth credentials are saved (provider can boot).
	 */
	public static function isProviderConfigured( string $module_id ): bool {
		if ( ! in_array( $module_id, self::SOCIAL_MODULE_IDS, true ) || ! self::isModuleEnabled( $module_id ) ) {
			return false;
		}
		$raw = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
		return match ( $module_id ) {
			'google-sign-in'   => self::hasCredentials( $raw, 'client_id', 'client_secret' ),
			'facebook-sign-in' => self::hasCredentials( $raw, 'app_id', 'app_secret' ),
			'github-sign-in'   => self::hasCredentials( $raw, 'client_id', 'client_secret' ),
			default            => false,
		};
	}

	/**
	 * @return list<string> Module ids with credentials configured.
	 */
	public static function getActiveSocialModules(): array {
		$out = [];
		foreach ( self::SOCIAL_MODULE_IDS as $id ) {
			if ( self::isProviderConfigured( $id ) ) {
				$out[] = $id;
			}
		}
		return $out;
	}

	public static function anySocialActive(): bool {
		return self::getActiveSocialModules() !== [];
	}

	/**
	 * @param array<string, mixed> $settings
	 */
	private static function hasCredentials( array $settings, string $id_key, string $secret_key ): bool {
		return trim( (string) ( $settings[ $id_key ] ?? '' ) ) !== ''
			&& trim( (string) ( $settings[ $secret_key ] ?? '' ) ) !== '';
	}
}
