<?php
/**
 * Brevo transactional email API provider.
 *
 * @package EmailSmtp
 * @link https://developers.brevo.com/docs/getting-started
 * @link https://developers.brevo.com/reference/send-transac-email
 */

namespace EmailSmtp\Providers\Brevo;

use EmailSmtp\Includes\AbstractApiProvider;
use EmailSmtp\Includes\ApiHttpClient;
use EmailSmtp\Includes\DeliveryResult;
use EmailSmtp\Includes\EmailMessage;
use EmailSmtp\Includes\ErrorNormalizer;

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

final class Provider extends AbstractApiProvider {

	/** Max recipients per role on a single /smtp/email send (messageVersions cap). */
	private const RECIPIENT_CAP = 99;

	public function get_id(): string {
		return 'brevo';
	}

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

	public function get_description(): string {
		return __( 'Send transactional email through the Brevo API v3.', 'wp-powersuite' );
	}

	public function get_recommended_use(): string {
		return __( 'Transactional mail with marketing platform overlap.', 'wp-powersuite' );
	}

	public function get_docs_url(): string {
		return 'https://developers.brevo.com/docs/send-a-transactional-email';
	}

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

	public function get_required_fields(): array {
		return [ 'brevo_api_key' ];
	}


	/**
	 * @param array<string, mixed> $settings
	 * @return array<string, string>
	 */
	private function auth_headers( array $settings ): array {
		$key = $this->secret( $settings, 'brevo_api_key', 'WP_POWERSUITE_BREVO_API_KEY' );
		return [
			'api-key'      => $key,
			'Accept'       => 'application/json',
			'Content-Type' => 'application/json',
		];
	}

	/**
	 * @param list<string> $emails
	 * @return list<array{email:string}>
	 */
	private function recipient_objects( array $emails ): array {
		return array_map(
			static fn( string $e ) => [ 'email' => $e ],
			array_slice( $emails, 0, self::RECIPIENT_CAP )
		);
	}

	public function connect( array $settings ): DeliveryResult {
		$key = $this->secret( $settings, 'brevo_api_key', 'WP_POWERSUITE_BREVO_API_KEY' );
		if ( $key === '' ) {
			return DeliveryResult::failure( __( 'Brevo API key is required.', 'wp-powersuite' ), '', 'authentication' );
		}

		$response = ApiHttpClient::request(
			'GET',
			'https://api.brevo.com/v3/account',
			$this->auth_headers( $settings )
		);

		return ApiHttpClient::to_delivery_result(
			$response,
			static function () {
				return [ 'message' => __( 'Brevo API key authenticated successfully.', 'wp-powersuite' ) ];
			}
		);
	}

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

		$key = $this->secret( $settings, 'brevo_api_key', 'WP_POWERSUITE_BREVO_API_KEY' );
		if ( $key === '' ) {
			return DeliveryResult::failure( __( 'Brevo API key is required.', 'wp-powersuite' ), '', 'authentication' );
		}

		$from    = $this->from_parts( $message );
		$payload = [
			'sender'  => array_filter(
				[
					'email' => $from['email'],
					'name'  => $from['name'] !== '' ? $from['name'] : null,
				]
			),
			'to'      => $this->recipient_objects( $message->get_to() ),
			'subject' => $message->get_subject(),
		];

		if ( $message->is_html() ) {
			$payload['htmlContent'] = $message->get_body();
			$payload['textContent'] = $message->get_alt_body() !== ''
				? $message->get_alt_body()
				: wp_strip_all_tags( $message->get_body() );
		} else {
			$payload['textContent'] = $message->get_body();
		}

		if ( $message->get_cc() !== [] ) {
			$payload['cc'] = $this->recipient_objects( $message->get_cc() );
		}
		if ( $message->get_bcc() !== [] ) {
			$payload['bcc'] = $this->recipient_objects( $message->get_bcc() );
		}
		if ( is_email( $message->get_reply_to_email() ) ) {
			$payload['replyTo'] = array_filter(
				[
					'email' => $message->get_reply_to_email(),
					'name'  => $message->get_reply_to_name() !== '' ? $message->get_reply_to_name() : null,
				]
			);
		}

		$attachments = $this->attachments_as_base64( $message );
		if ( $attachments !== [] ) {
			$payload['attachment'] = array_map(
				static function ( array $a ) {
					return [
						'content' => $a['content'],
						'name'    => $a['name'],
					];
				},
				$attachments
			);
		}

		// Custom headers object; Idempotency-Key is supported per Brevo docs.
		$headers = $this->safe_custom_headers( $message );
		$headers['Idempotency-Key'] = wp_generate_uuid4();
		$payload['headers']         = $headers;

		$response = ApiHttpClient::request(
			'POST',
			'https://api.brevo.com/v3/smtp/email',
			$this->auth_headers( $settings ),
			$payload
		);

		if ( ! empty( $response['error'] ) ) {
			return ErrorNormalizer::from_text( (string) $response['error'] );
		}

		return ApiHttpClient::to_delivery_result(
			$response,
			static function ( array $res ) {
				$id = '';
				if ( is_array( $res['json'] ) ) {
					$id = (string) ( $res['json']['messageId'] ?? '' );
					if ( $id === '' && ! empty( $res['json']['messageIds'] ) && is_array( $res['json']['messageIds'] ) ) {
						$id = (string) ( $res['json']['messageIds'][0] ?? '' );
					}
				}
				return [
					'message' => __( 'Brevo accepted the message.', 'wp-powersuite' ),
					'id'      => $id,
				];
			}
		);
	}
}
