<?php
/**
 * Base class for HTTP API email providers.
 *
 * @package EmailSmtp
 */

namespace EmailSmtp\Includes;

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

abstract class AbstractApiProvider extends AbstractProvider {

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

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

	/**
	 * @param array<string, mixed> $settings
	 */
	protected function secret( array $settings, string $key, string $constant = '' ): string {
		return CredentialManager::resolve( $settings, $key, $constant, $constant );
	}

	/**
	 * @return list<array{name:string, content:string, type:string}>
	 */
	protected function attachments_as_base64( EmailMessage $message ): array {
		$out = [];
		foreach ( $message->get_attachments() as $path ) {
			$path = (string) $path;
			if ( $path === '' || ! is_readable( $path ) ) {
				continue;
			}
			$contents = file_get_contents( $path ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
			if ( $contents === false ) {
				continue;
			}
			$name = basename( $path );
			$type = 'application/octet-stream';
			if ( function_exists( 'mime_content_type' ) ) {
				$detected = mime_content_type( $path );
				if ( is_string( $detected ) && $detected !== '' ) {
					$type = $detected;
				}
			}
			$out[] = [
				'name'    => $name,
				'content' => base64_encode( $contents ),
				'type'    => $type,
			];
		}
		return $out;
	}

	protected function format_address( string $email, string $name = '' ): string {
		$email = sanitize_email( $email );
		$name  = sanitize_text_field( $name );
		if ( ! is_email( $email ) ) {
			return '';
		}
		if ( $name === '' ) {
			return $email;
		}
		return sprintf( '%s <%s>', $name, $email );
	}

	/**
	 * @return array{email:string, name:string}
	 */
	protected function from_parts( EmailMessage $message ): array {
		$email = $message->get_from_email();
		if ( ! is_email( $email ) ) {
			$email = sanitize_email( (string) get_option( 'admin_email' ) );
		}
		return [
			'email' => $email,
			'name'  => $message->get_from_name(),
		];
	}

	protected function require_from( EmailMessage $message ): ?DeliveryResult {
		$from = $this->from_parts( $message );
		if ( ! is_email( $from['email'] ) ) {
			return DeliveryResult::failure(
				__( 'A valid From email address is required.', 'wp-powersuite' ),
				'missing_from',
				'sender',
				'',
				false,
				__( 'Set From email in the Sender tab and verify it with your provider.', 'wp-powersuite' )
			);
		}
		if ( $message->get_to() === [] ) {
			return DeliveryResult::failure(
				__( 'At least one recipient is required.', 'wp-powersuite' ),
				'missing_to',
				'recipient'
			);
		}
		return null;
	}

	/**
	 * @return array<string, string>
	 */
	protected function safe_custom_headers( EmailMessage $message ): array {
		$blocked = [ 'authorization', 'api-key', 'x-api-key', 'cookie', 'set-cookie' ];
		$out     = [];
		foreach ( $message->get_custom_headers() as $name => $value ) {
			$key = strtolower( (string) $name );
			if ( in_array( $key, $blocked, true ) ) {
				continue;
			}
			$out[ (string) $name ] = sanitize_text_field( (string) $value );
		}
		return $out;
	}

	protected function plain_text_body( EmailMessage $message ): string {
		if ( ! $message->is_html() ) {
			$body = $message->get_body();
			return $body !== '' ? $body : ' ';
		}
		if ( $message->get_alt_body() !== '' ) {
			return $message->get_alt_body();
		}
		$stripped = wp_strip_all_tags( $message->get_body() );
		return $stripped !== '' ? $stripped : ' ';
	}

	/**
	 * @param list<string> $emails
	 * @return list<string>
	 */
	protected function take_recipients( array $emails, int &$remaining ): array {
		if ( $remaining <= 0 || $emails === [] ) {
			return [];
		}
		$slice      = array_slice( $emails, 0, $remaining );
		$remaining -= count( $slice );
		return $slice;
	}
}
