<?php

declare(strict_types=1);

namespace FormConnector\Core\Utils;

/**
 * Debug logging helpers.
 *
 * All plugin code should route diagnostic messages through these helpers
 * instead of calling error_log() directly, so high-traffic sites don't fill
 * their PHP error logs with informational chatter.
 *
 * Messages are only written when WP_DEBUG is enabled (or the
 * `FC_FORCE_DEBUG_LOG` constant is defined and truthy).
 */
class Debug {

	/**
	 * Whether diagnostic logging is currently enabled.
	 */
	public static function is_enabled(): bool {
		if (defined('FC_FORCE_DEBUG_LOG') && FC_FORCE_DEBUG_LOG) {
			return true;
		}

		return defined('WP_DEBUG') && WP_DEBUG;
	}

	/**
	 * Write a single diagnostic line.
	 *
	 * @param string              $message Free-form message; do not include the [FormConnector] prefix.
	 * @param array<string,mixed> $context Optional structured context appended as JSON.
	 */
	public static function log(string $message, array $context = []): void {
		if (!self::is_enabled()) {
			return;
		}

		$line = '[FormConnector] ' . $message;
		if (!empty($context)) {
			$encoded = wp_json_encode($context);
			if (is_string($encoded)) {
				$line .= ' ' . $encoded;
			}
		}

		// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
		error_log($line);
	}

	/**
	 * Convenience: warn-level message (still gated by WP_DEBUG).
	 */
	public static function warn(string $message, array $context = []): void {
		self::log('WARN: ' . $message, $context);
	}

	/**
	 * Convenience: error-level message (still gated by WP_DEBUG).
	 *
	 * For genuine end-user errors, surface them in the response payload
	 * and/or the dedicated error log table — not here.
	 */
	public static function error(string $message, array $context = []): void {
		self::log('ERROR: ' . $message, $context);
	}
}

/**
 * Procedural shorthand mirroring WordPress' own helper conventions.
 *
 * @param string              $message
 * @param array<string,mixed> $context
 */
function fc_debug_log(string $message, array $context = []): void {
	Debug::log($message, $context);
}
