<?php
/**
 * Extends the WooCommerce logger to log to the Shared logger.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Modules\Loggers\WC;

use Northmill_Online_Shared\Abstract_Shared_Base;
use Northmill_Online_Shared\Modules\Logger_Module;
use Northmill_Online_Shared\Modules\Loggers\Log_Level_Enum;
use Throwable;
use WC_Logger;

/**
 * Class WC_Extended_Logger
 */
class WC_Extended_Logger extends WC_Logger {

	/**
	 * Log data to the WooCommerce logger and DataDog.
	 *
	 * @param string $level   Log level.
	 * @param string $message The message to be logged.
	 * @param array  $context The data to be logged.
	 *
	 * @return void
	 */
	public function log( $level, $message, $context = array() ): void {
		// We can't process messages without "source" using the Shared logger.
		if ( empty( $context['source'] ) ) {
			parent::log( $level, $message, $context );
			return;
		}

		// This has already been handled by the Shared logger, prevent infinite loop.
		if ( ! empty( $context[ Logger_Module::LOG_HANDLED_KEY ] ) ) {
			unset( $context[ Logger_Module::LOG_HANDLED_KEY ] );

			parent::log( $level, $message, $context );
			return;
		}

		// Now we know this is a log coming from somewhere else than the Shared logger module.
		$this->handle_with_shared_logger( $level, $message, $context );
	}

	/**
	 * Log to DataDog.
	 *
	 * @param string $level   Log level.
	 * @param string $message The message to be logged.
	 * @param array  $context The data to be logged.
	 *
	 * @return void
	 */
	private function handle_with_shared_logger( string $level, string $message, array $context ): void {

		try {
			$log_level = Log_Level_Enum::from( $level );
		} catch ( Throwable ) {
			parent::log( $level, $message, $context );
			return;
		}

		Abstract_Shared_Base::base_instance()->logger->log(
			$context['source'],
			$message,
			$context,
			$log_level,
			true
		);
	}
}
