<?php
/**
 * Request-scoped metadata for the current outbound delivery attempt.
 *
 * Used so Email Logs / diagnostics can record transport, connection, and envelope
 * without leaking credentials.
 *
 * @package EmailSmtp
 */

namespace EmailSmtp\Includes;

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

final class DeliveryAttemptContext {

	/** @var array<string, mixed> */
	private static array $data = [];

	/**
	 * @param array<string, mixed> $data
	 */
	public static function begin( array $data ): void {
		self::$data = array_merge(
			[
				'transport'           => '',
				'provider'            => '',
				'connection_id'       => '',
				'connection_name'     => '',
				'from_email'          => '',
				'envelope_sender'     => '',
				'routing_reason'      => '',
				'fallback_used'       => 0,
				'retry_count'         => 0,
				'orchestrated'        => 0,
				'phpmailer_mailer'    => '',
			],
			$data
		);
	}

	/**
	 * @param array<string, mixed> $data
	 */
	public static function merge( array $data ): void {
		self::$data = array_merge( self::$data, $data );
	}

	/**
	 * @return array<string, mixed>
	 */
	public static function all(): array {
		return self::$data;
	}

	public static function get( string $key, mixed $default = '' ): mixed {
		return self::$data[ $key ] ?? $default;
	}

	public static function clear(): void {
		self::$data = [];
	}

	/**
	 * Safe subset for Email Logs enrichment (no secrets).
	 *
	 * @return array<string, mixed>
	 */
	public static function for_log(): array {
		$allowed = [
			'transport',
			'provider',
			'connection_id',
			'connection_name',
			'from_email',
			'envelope_sender',
			'routing_reason',
			'fallback_used',
			'retry_count',
			'orchestrated',
			'phpmailer_mailer',
			'provider_message_id',
			'duration_ms',
			'delivery_status',
			'trigger_source',
		];
		$out = [];
		foreach ( $allowed as $key ) {
			if ( array_key_exists( $key, self::$data ) ) {
				$out[ $key ] = self::$data[ $key ];
			}
		}
		return $out;
	}
}
