<?php
/**
 * Global API Helper Function
 *
 * Provides a simple global function for integration packages to get
 * authenticated API clients without any core class imports.
 *
 * @package Sequensy
 * @since 2.0.0
 */

declare(strict_types=1);

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

/**
 * Get an authenticated API client for an integration package.
 *
 * Array-based packages call this from their action handlers:
 *   $api = sequensy_api('slack');
 *   $result = $api->post('chat.postMessage', [...]);
 *
 * Checks for a registered api_factory closure first (new array-based packages),
 * then falls back to the legacy class-based approach.
 *
 * @param string      $slug          Integration slug (e.g., 'campaignmonitor', 'slack').
 * @param string|null $connection_id Optional connection ID for multi-account support.
 *                                   If null, uses the first available connection.
 * @return object API client instance.
 * @throws \RuntimeException If integration is not configured or has no credentials.
 */
function sequensy_api( string $slug, ?string $connection_id = null ): object {
	// Try new api_factory approach first.
	$factory = \Sequensy\Integrations\IntegrationStorage::get_api_factory( $slug );

	if ( null !== $factory ) {
		// Resolve connection_id for factory approach: if null, use first available.
		if ( null === $connection_id ) {
			$first = \Sequensy\Integrations\IntegrationStorage::get_first_connection( $slug );
			if ( null === $first ) {
				throw new \RuntimeException(
					sprintf( 'No connections found for integration: %s', esc_attr( $slug ) )
				);
			}
			$connection_id = $first['id'];
		}

		$credentials = \Sequensy\Integrations\IntegrationStorage::get_connection_credentials( $slug, $connection_id );

		if ( empty( $credentials ) ) {
			throw new \RuntimeException(
				sprintf( 'No credentials found for integration: %s', esc_attr( $slug ) )
			);
		}

		return $factory( $credentials );
	}

	// Fallback to legacy class-based approach (handles null connection_id internally).
	$class = \Sequensy\Integrations\IntegrationStorage::get_integration_class( $slug );

	if ( $class && class_exists( $class ) && method_exists( $class, 'get_api' ) ) {
		$api = $class::get_api( $connection_id );

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

		return $api;
	}

	throw new \RuntimeException(
		sprintf( 'Integration not configured: %s', esc_attr( $slug ) )
	);
}
