<?php
/**
 * Gated diagnostic logging.
 *
 * @package Carticy\Conversions\Support
 */

declare(strict_types=1);

namespace Carticy\Conversions\Support;

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

/**
 * Thin wrapper over wc_get_logger() for capture/dispatch/hydration decisions.
 *
 * Errors always log (a swallowed exception must leave a trace); debug-level
 * decision traces log only when the merchant enables the toggle. Context
 * values must already be redacted by the caller: never pass secrets, raw
 * payloads, or customer PII.
 */
final class DiagnosticLogger {

	public const SOURCE       = 'carticy-conversions';
	public const DEBUG_OPTION = 'carticy_conversions_debug_log';

	/**
	 * Log an error. Always recorded when a logger exists.
	 *
	 * @param string               $message Message.
	 * @param array<string, mixed> $context Pre-redacted context.
	 */
	public static function error( string $message, array $context = array() ): void {
		self::write( 'error', $message, $context );
	}

	/**
	 * Log a debug decision trace. Recorded only when the toggle is on.
	 *
	 * @param string               $message Message.
	 * @param array<string, mixed> $context Pre-redacted context.
	 */
	public static function debug( string $message, array $context = array() ): void {
		if ( ! self::debug_enabled() ) {
			return;
		}

		self::write( 'debug', $message, $context );
	}

	/**
	 * Whether debug tracing is enabled.
	 *
	 * @return bool
	 */
	public static function debug_enabled(): bool {
		return function_exists( 'get_option' ) && 'yes' === get_option( self::DEBUG_OPTION, 'no' );
	}

	/**
	 * Write a log entry through WooCommerce's logger when available.
	 *
	 * @param string               $level Log level.
	 * @param string               $message Message.
	 * @param array<string, mixed> $context Pre-redacted context.
	 */
	private static function write( string $level, string $message, array $context ): void {
		if ( ! function_exists( 'wc_get_logger' ) ) {
			return;
		}

		$logger = wc_get_logger();
		if ( ! is_object( $logger ) || ! method_exists( $logger, 'log' ) ) {
			return;
		}

		$context['source'] = self::SOURCE;
		$logger->log( $level, $message, $context );
	}
}
