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

namespace Hafenstudios\Kurato\Mail;

use Hafenstudios\Core\Mail\Message;

defined( 'ABSPATH' ) || exit;

/**
 * Brevo-Versandtreiber (EU-Default). Transaktionale Brevo-API, nur Einzelmail,
 * kein Kontakt-Sync (Datenhoheit bleibt in WordPress, K4-Konzept Abschnitt 1).
 */
final class BrevoDriver extends AbstractApiEspDriver {

	private string $api_key;

	/**
	 * @param string $api_key Brevo-API-Key (Klartext).
	 */
	public function __construct( string $api_key ) {
		$this->api_key = $api_key;
	}

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

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

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

	/**
	 * @return string
	 */
	protected function config_error(): string {
		return __( 'Kein Brevo-API-Key hinterlegt.', 'kurato' );
	}

	/**
	 * @param Message $message Nachricht.
	 * @return array{headers:array<string,string>,body:string}
	 */
	protected function build_request( Message $message ): array {
		$sender = array( 'email' => $message->from_email );
		if ( '' !== $message->from_name ) {
			$sender['name'] = $message->from_name;
		}

		$body = array(
			'sender'  => $sender,
			'to'      => array( array( 'email' => $message->to ) ),
			'subject' => $message->subject,
		);
		if ( $message->is_html ) {
			$body['htmlContent'] = $message->body;
			// Multipart: Klartext-Alternative als textContent mitsenden (Brevo).
			if ( '' !== $message->text_body ) {
				$body['textContent'] = $message->text_body;
			}
		} else {
			$body['textContent'] = $message->body;
		}
		if ( '' !== $message->reply_to ) {
			$body['replyTo'] = array( 'email' => $message->reply_to );
		}
		if ( array() !== $message->headers ) {
			$body['headers'] = $message->headers;
		}

		return array(
			'headers' => array(
				'api-key'      => $this->api_key,
				'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' );
	}
}
