<?php
/**
 * Subscriber Helper
 *
 * Resolves email addresses to Kit subscriber IDs.
 *
 * @package Sequensy\Integrations\Kit
 * @since 1.0.0
 */

declare(strict_types=1);

namespace Sequensy\Integrations\Kit\Helpers;

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Class SubscriberHelper
 *
 * Provides shared subscriber resolution logic for Kit actions.
 */
class SubscriberHelper {

	/**
	 * Resolve an email address to a Kit subscriber ID.
	 *
	 * Looks up the subscriber by email via the Kit API and returns
	 * the subscriber ID. Throws a RuntimeException if the subscriber
	 * is not found or the API call fails.
	 *
	 * @param string $email_address Email address to look up.
	 * @return int Subscriber ID.
	 *
	 * @throws \RuntimeException If the subscriber cannot be found or the API call fails.
	 */
	public static function resolve_subscriber_id( string $email_address ): int {
		$result = sequensy_api( 'kit' )->get_subscriber_by_email( $email_address );

		if ( is_wp_error( $result ) ) {
			throw new \RuntimeException( esc_html( $result->get_error_message() ) );
		}

		$subscribers = $result['data']['subscribers'] ?? array();

		if ( empty( $subscribers ) ) {
			throw new \RuntimeException(
				sprintf(
					/* translators: %s: email address */
					esc_html__( 'No subscriber found with email: %s', 'sequensy' ),
					esc_html( $email_address )
				)
			);
		}

		return (int) $subscribers[0]['id'];
	}
}
