<?php
/**
 * WooCommerce Logger
 *
 * @package northmill-online-shared
 *
 * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamTag
 */

namespace Northmill_Online_Shared\Modules\Loggers;

use Northmill_Online_Shared\Abstract_Shared_Base;
use Northmill_Online_Shared\Modules\Logger_Module;
use WC_Logger_Interface;

/**
 * Class WooCommerce_Logger
 */
class WooCommerce_Logger extends Abstract_Logger {

	/**
	 * Get prefix for internal logging.
	 *
	 * @return string
	 */
	public static function get_source_prefix(): string {
		return Abstract_Shared_Base::base_instance()->package_info->get_service_name() . '-';
	}

	/**
	 * {@inerhitDoc}
	 */
	public function log(
		string $channel,
		string $message,
		?array $context,
		Log_Level_Enum $level,
		bool $external_log = false
	): void {
		if ( ! function_exists( 'wc_get_logger' ) ) {
			return;
		}

		if ( ! $context ) {
			$context = array();
		} else {
			foreach ( $context as &$item ) {
				if ( is_wp_error( $item ) ) {
					$item = $item->get_error_message();
				}
			}
			unset( $item );
		}

		if ( $external_log ) {
			$source = $channel;
		} else {
			$source = self::get_source_prefix() . $channel;

			if ( Log_Level_Enum::DEBUG === $level ) {
				$source .= '-debug';
			}
		}

		$context['source']                         = $source;
		$context[ Logger_Module::LOG_HANDLED_KEY ] = true;

		/**
		 * Instance of WC Logger.
		 *
		 * @var WC_Logger_Interface $wc_logger
		 */
		$wc_logger = wc_get_logger();
		$wc_logger->log(
			$level->value,
			$message,
			$context
		);
	}
}
