<?php
/**
 * Template repository for Mail Doctor email overrides.
 *
 * @package MailDoctor
 */

namespace MailDoctor\Email;

use MailDoctor\WPMD_Email_Templates;

/**
 * Provides read-only access to template metadata without changing storage.
 */
class TemplateRepository {
	/**
	 * In-process memo cache.
	 *
	 * @var array<string, Template|null>
	 */
	private static array $memo = array();

	public static function flush_cache(): void {
		self::$memo = array();
	}

	public function is_enabled(): bool {
		return WPMD_Email_Templates::is_enabled();
	}

	/**
	 * @return array<string,string>
	 */
	public function get_supported_email_types(): array {
		return WPMD_Email_Templates::get_supported_email_types();
	}

	/**
	 * Persist a historical snapshot for a template.
	 *
	 * @param Template             $template Template instance.
	 * @param array<string, mixed> $context  Context such as post_id/editor_mode.
	 * @return string|null
	 */
	public function record_history( Template $template, array $context = array() ): ?string {
		return TemplateHistory::record( $template, $context );
	}

	/**
	 * Retrieve stored versions for a template.
	 *
	 * @param int|string $template_id Template identifier.
	 * @param int        $limit       Maximum versions.
	 * @return array<int, array<string, mixed>>
	 */
	public function list_history( $template_id, int $limit = 20 ): array {
		return TemplateHistory::list_versions( $template_id, $limit );
	}

	/**
	 * Fetch a specific version payload.
	 *
	 * @param string $version_id Version identifier.
	 * @return array<string, mixed>|null
	 */
	public function get_version( string $version_id ): ?array {
		return TemplateHistory::get( $version_id );
	}

	/**
	 * Restore a captured version.
	 *
	 * @param string $version_id Version identifier.
	 * @return Template|null
	 */
	public function restore_version( string $version_id ): ?Template {
		return TemplateHistory::restore( $version_id );
	}

	public function find_active_template( string $email_id, string $locale ): ?Template { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterface
		$email_id = sanitize_key( $email_id );
		$locale   = (string) $locale;

		if ( '' === $email_id ) {
			return null;
		}

		$key = $email_id . '|' . ( '' !== $locale ? $locale : 'default' );

		if ( ! $this->is_enabled() ) {
			self::flush_cache();
			return null;
		}

		if ( array_key_exists( $key, self::$memo ) ) {
			return self::$memo[ $key ];
		}

		$data = WPMD_Email_Templates::get_template_data( $email_id );

		if ( empty( $data ) || ! is_array( $data ) ) {
			self::$memo[ $key ] = null;
			return null;
		}

		$template           = new Template( $email_id, $data );
		self::$memo[ $key ] = $template;

		return $template;
	}
}
