<?php
/**
 * Override resolver coordinating template lookups.
 *
 * @package MailDoctor
 */

namespace MailDoctor\Email;

use WC_Email;

/**
 * Determines whether custom templates should override WooCommerce output.
 */
class OverrideResolver {
	public const VERSION = 'v1';

	private TemplateRepository $repository;

	public function __construct( TemplateRepository $repository ) {
		$this->repository = $repository;
	}

	public static function version(): string {
		return self::VERSION;
	}

	public function resolve( WC_Email $email, string $locale ): ?ResolvedTemplate {
		if ( ! $this->repository->is_enabled() ) {
			do_action( 'mail_doctor_email_template_resolved', $email->id ?? '', $locale, null );
			return null;
		}

		$email_id = isset( $email->id ) ? (string) $email->id : '';

		if ( '' === $email_id ) {
			do_action( 'mail_doctor_email_template_resolved', '', $locale, null );
			return null;
		}

		$template = $this->repository->find_active_template( $email_id, $locale );

		if ( null === $template ) {
			do_action( 'mail_doctor_email_template_resolved', $email_id, $locale, null );
			return null;
		}

		$resolved = new ResolvedTemplate( $template, $locale );

		do_action( 'mail_doctor_email_template_resolved', $email_id, $locale, $resolved );

		return $resolved;
	}
}
