<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Mail;

use Hafenstudios\Core\Mail\Message;

defined( 'ABSPATH' ) || exit;

/**
 * Postmark-Versandtreiber. Sehr gute Deliverability und Bounce-Webhooks,
 * einfache API mit Server-Token.
 */
final class PostmarkDriver extends AbstractApiEspDriver {

	private string $token;

	/**
	 * @param string $token Postmark-Server-Token.
	 */
	public function __construct( string $token ) {
		$this->token = $token;
	}

	/**
	 * @return string
	 */
	public function key(): string {
		return 'postmark';
	}

	/**
	 * @return string
	 */
	protected function endpoint(): string {
		return 'https://api.postmarkapp.com/email';
	}

	/**
	 * @return bool
	 */
	protected function is_configured(): bool {
		return '' !== $this->token;
	}

	/**
	 * @return string
	 */
	protected function config_error(): string {
		return __( 'Kein Postmark-Server-Token hinterlegt.', 'kurato' );
	}

	/**
	 * @param Message $message Nachricht.
	 * @return array{headers:array<string,string>,body:string}
	 */
	protected function build_request( Message $message ): array {
		$from = '' !== $message->from_name
			? sprintf( '%s <%s>', $message->from_name, $message->from_email )
			: $message->from_email;

		$body = array(
			'From'    => $from,
			'To'      => $message->to,
			'Subject' => $message->subject,
		);
		if ( $message->is_html ) {
			$body['HtmlBody'] = $message->body;
			// Multipart: Klartext-Alternative als TextBody mitsenden (Postmark).
			if ( '' !== $message->text_body ) {
				$body['TextBody'] = $message->text_body;
			}
		} else {
			$body['TextBody'] = $message->body;
		}
		if ( '' !== $message->reply_to ) {
			$body['ReplyTo'] = $message->reply_to;
		}
		if ( array() !== $message->headers ) {
			$headers = array();
			foreach ( $message->headers as $name => $value ) {
				$headers[] = array( 'Name' => $name, 'Value' => $value );
			}
			$body['Headers'] = $headers;
		}

		return array(
			'headers' => array(
				'X-Postmark-Server-Token' => $this->token,
				'Content-Type'            => 'application/json',
				'Accept'                  => 'application/json',
			),
			'body'    => (string) wp_json_encode( $body ),
		);
	}

	/**
	 * @param string $body Response-Body.
	 * @return string
	 */
	protected function parse_message_id( string $body ): string {
		return $this->json_value( $body, 'MessageID' );
	}
}
