<?php
/**
 * Integrations factory for creating integration instances.
 *
 * @package Awesomemotive\Rewardswp\Factories
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Factories;

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

use Awesomemotive\Rewardswp\Integrations\UnknownIntegration;
use Awesomemotive\Rewardswp\Interfaces\IntegrationInterface;
use DI\Container;
use Exception;
use function Awesomemotive\Rewardswp\Helpers\str_snake_to_pascal_case;

class IntegrationsFactory {
	/**
	 * Dependency injection container.
	 *
	 * @since 1.0.0
	 *
	 * @var Container
	 */
	private Container $container;

	public function __construct( Container $container ) {
		$this->container = $container;
	}

	/**
	 * Retrieves an instance of an Integration object based on the integration name.
	 *
	 * @since 1.0.0
	 *
	 * @param string|IntegrationInterface $name_or_class The snake_case name of the integration or the class name.
	 * @return IntegrationInterface|null                 The Integration object instance, or null if not found.
	 */
	function get_integration( $name_or_class ): ?IntegrationInterface {
		try {
			// Check if it is the class name, if so, return right away.
			if ( class_exists( $name_or_class ) && is_subclass_of( $name_or_class, IntegrationInterface::class ) ) {
				return $this->container->get( $name_or_class );
			}

			$full_class_name = sprintf(
				'Awesomemotive\\Rewardswp\\Integrations\\%s',
				sprintf( '%sIntegration', str_snake_to_pascal_case( $name_or_class ) )
			);

			if ( class_exists( $full_class_name ) && is_subclass_of( $full_class_name, IntegrationInterface::class ) ) {
				return $this->container->get( $full_class_name );
			}

			return $this->container->get( UnknownIntegration::class );
		} catch ( Exception $exception ) {
			return null;
		}
	}
}
