<?php
/**
 * Structured logging exporter for Mail Doctor.
 *
 * @package MailDoctor
 */

namespace MailDoctor;

use MailDoctor\Helpers\Settings;

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

/**
 * Sends anonymised events to external observability endpoints.
 */
class Exporter {


	/**
	 * Trigger export for a log entry if enabled.
	 *
	 * @param int $log_id Log identifier.
	 * @return void
	 */
	public static function maybe_export( int $log_id ): void {
		if ( class_exists( '\\MailDoctor\\Features' ) && ! \MailDoctor\Features::is_enabled( 'structured_logging' ) ) {
			return;
		}

		$settings = Settings::all();

		if ( empty( $settings['structured_logging_enabled'] ) ) {
			return;
		}

		$endpoint = isset( $settings['structured_logging_endpoint'] ) ? esc_url_raw( $settings['structured_logging_endpoint'] ) : '';

		if ( empty( $endpoint ) ) {
			return;
		}

		global $wpdb;
		$table = Logger::table_name();

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Exporter fetches fresh log data.
		$row = $wpdb->get_row(
			$wpdb->prepare(
				// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
				"SELECT id, created_at, event, order_id, to_email, status, provider_code, duration_ms, error FROM {$table} WHERE id = %d",
				$log_id
			),
			ARRAY_A
		);

		if ( ! $row ) {
			return;
		}

		$domain = '';
		if ( ! empty( $row['to_email'] ) ) {
			$email_parts = explode( '@', trim( $row['to_email'] ) );
			$domain      = isset( $email_parts[1] ) ? strtolower( $email_parts[1] ) : '';
		}

		$meta        = Logger::get_payload( (int) $row['id'] );
		$email_class = '';
		if ( ! empty( $meta['meta']['email_class'] ) ) {
			$email_class = sanitize_text_field( (string) $meta['meta']['email_class'] );
		}

		$payload = array(
			'id'               => (int) $row['id'],
			'created_at'       => $row['created_at'],
			'status'           => $row['status'],
			'event'            => $row['event'],
			'order_id'         => $row['order_id'] ? (int) $row['order_id'] : null,
			'recipient_domain' => $domain,
			'provider_code'    => $row['provider_code'],
			'duration_ms'      => $row['duration_ms'] ? (int) $row['duration_ms'] : null,
			'email_class'      => $email_class ?: null,
			'error'            => $row['error'] ?? null,
		);

		$headers = array( 'Content-Type' => 'application/json' );
		if ( ! empty( $settings['structured_logging_token'] ) ) {
			$headers['Authorization'] = 'Bearer ' . trim( $settings['structured_logging_token'] );
		}

		wp_remote_post(
			$endpoint,
			array(
				'timeout'  => 5,
				'blocking' => false,
				'headers'  => $headers,
				'body'     => wp_json_encode(
					array(
						'source' => 'mail-doctor',
						'event'  => $payload,
					)
				),
			)
		);
	}
}
