<?php
/**
 * A factory that builds a wrapper around the mail providers.
 *
 * @since 3.0.0
 */

declare(strict_types=1);
namespace FeData\FastEvents\Mail;

defined( 'ABSPATH' ) || exit;

use FeData\FastEvents\Logging\LoggerFactory;
use FeData\FastEvents\Storage\PluginSettings;

/**
 * A class for creating a reference to the used mail provider in the plugin settings.
 *
 * @mixin MailerInterface
 */
final class MailerFactory {

	/**
	 * Mail provider that implemented the MailerInterface.
	 *
	 * @since 2.5.0
	 * @var MailerInterface
	 */
	private MailerInterface $mailer;

	/**
	 * MailerFactory constructor.
	 *
	 * @since 3.0.0
	 *
	 * @param PluginSettings $settings Plugin settings.
	 * @param LoggerFactory  $logger   Logger.
	 */
	public function __construct( private readonly PluginSettings $settings, private readonly LoggerFactory $logger ) {
		global $fevt_container;

		$config = $this->settings->mailer_config();

		if ( empty( $config->provider->class ) ) {
			$this->logger->alert( __( 'Empty mail provider class', 'fast-events' ) );
		}
		$class = $config->provider->class;
		if ( ! class_exists( $class ) ) {
			/* translators: %d is the class name */
			$this->logger->alert( sprintf( esc_html__( 'Mailer class "%1$s" not found', 'fast-events' ), $config->provider->class ) );
		}
		$this->mailer = $fevt_container->get( $class );
	}

	/**
	 * Singletons should not be cloneable.
	 *
	 * @since 2.5.0
	 */
	private function __clone(): void {}

	/**
	 * Prevent from being unserialized.
	 *
	 * @since 2.5.0
	 */
	public function __wakeup(): void {}

	/**
	 * Forward any other method to the mail provider.
	 *
	 * @since 2.5.0
	 *
	 * @param string $method Provider method name.
	 * @param array  $args   Arguments.
	 * @return mixed
	 */
	public function __call( string $method, array $args ) {
		return $this->mailer->$method( ...$args );
	}
}
