<?php
/**
 * Base email delivery provider.
 *
 * @package EmailSmtp
 */

namespace EmailSmtp\Includes;

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

abstract class AbstractProvider implements ProviderInterface {

	public function get_transport_label(): string {
		return __( 'API', 'wp-powersuite' );
	}

	public function get_recommended_use(): string {
		return '';
	}

	public function get_docs_url(): string {
		return '';
	}

	public function get_icon(): string {
		return 'dashicons-email-alt';
	}

	/**
	 * @param array<string, mixed> $settings
	 * @return true|\WP_Error
	 */
	public function validate_settings( array $settings ) {
		foreach ( $this->get_required_fields() as $field ) {
			$value = $settings[ $field ] ?? '';
			if ( is_string( $value ) && trim( $value ) === '' ) {
				return new \WP_Error(
					'missing_field',
					sprintf(
						/* translators: %s: field key */
						__( 'Missing required field: %s', 'wp-powersuite' ),
						$field
					)
				);
			}
		}

		return true;
	}

	public function connect( array $settings ): DeliveryResult {
		$valid = $this->validate_settings( $settings );
		if ( is_wp_error( $valid ) ) {
			return DeliveryResult::failure(
				$valid->get_error_message(),
				$valid->get_error_message(),
				'validation',
				(string) $valid->get_error_code(),
				false,
				__( 'Complete the required provider settings and try again.', 'wp-powersuite' )
			);
		}

		return DeliveryResult::success( __( 'Configuration looks complete.', 'wp-powersuite' ) );
	}

	public function disconnect( array $settings ): array {
		return $settings;
	}

	public function send_test( EmailMessage $message, array $settings ): DeliveryResult {
		return $this->send( $message, $settings );
	}

	public function get_connection_status( array $settings ): string {
		$valid = $this->validate_settings( $settings );
		if ( is_wp_error( $valid ) ) {
			$required = $this->get_required_fields();
			$any      = false;
			foreach ( $required as $field ) {
				$value = $settings[ $field ] ?? '';
				if ( is_string( $value ) && trim( $value ) !== '' ) {
					$any = true;
					break;
				}
			}
			return $any ? 'incomplete' : 'not_configured';
		}

		return 'connected';
	}

	public function normalize_error( $error ): DeliveryResult {
		return ErrorNormalizer::from_mixed( $error );
	}

	public function supports_attachments(): bool {
		return true;
	}

	public function supports_html(): bool {
		return true;
	}

	public function supports_reply_to(): bool {
		return true;
	}

	public function supports_custom_headers(): bool {
		return true;
	}

	public function supports_tags(): bool {
		return false;
	}

	public function supports_metadata(): bool {
		return false;
	}

	public function supports_batching(): bool {
		return false;
	}

	public function uses_phpmailer_smtp(): bool {
		return false;
	}

	public function uses_api_transport(): bool {
		return false;
	}
}
