<?php
namespace flow\social\publisher;
if (!defined('WPINC'))
	die;

/**
 * Flow-Flow Publishing Dispatcher.
 *
 * Receives a composed post and dispatches it to one or more
 * network-specific publishers. Collects results for each network.
 *
 * @package   FlowFlow
 * @author    Looks Awesome <email@looks-awesome.com>
 * @link      http://looks-awesome.com
 * @copyright Looks Awesome
 */
class FFPublishDispatcher {

	/** @var FFPublisherInterface[] Registered publishers keyed by network. */
	private $publishers = [];

	public function __construct() {
		$this->publishers = [
			'facebook'  => new FFFacebookPublisher(),
			'instagram' => new FFInstagramPublisher(),
			'linkedin'  => new FFLinkedInPublisher(),
			'youtube'   => new FFYoutubePublisher(),
		];
	}

	/**
	 * Get the list of supported network identifiers.
	 *
	 * @return string[]
	 */
	public function getSupportedNetworks() {
		return array_keys($this->publishers);
	}

	/**
	 * Get human-readable labels for networks.
	 *
	 * @return array<string, string>
	 */
	public static function getNetworkLabels() {
		return [
			'facebook'  => 'Facebook',
			'instagram' => 'Instagram',
			'linkedin'  => 'LinkedIn',
			'youtube'   => 'YouTube',
		];
	}

	/**
	 * Dispatch a post to the specified networks.
	 *
	 * @param array    $postData  Common post data (text, media, link, extra).
	 * @param array    $targets   Array of target configs: [ { network, account_id, token } ]
	 *
	 * @return array   Keyed by network → result array from the publisher.
	 */
	public function dispatch(array $postData, array $targets) {
		$results = [];

		foreach ($targets as $target) {
			$network   = isset($target['network']) ? $target['network'] : '';
			$accountId = isset($target['account_id']) ? $target['account_id'] : '';
			$token     = isset($target['token']) ? $target['token'] : '';

			if (!isset($this->publishers[$network])) {
				$results[$network] = [
					'success' => false,
					'error'   => "Unsupported network: {$network}",
				];
				continue;
			}

			$publisher = $this->publishers[$network];
			$payload   = array_merge($postData, [
				'account_id' => $accountId,
				'token'      => $token,
			]);

			try {
				$results[$network] = $publisher->publish($payload);
			} catch (\Exception $e) {
				$results[$network] = [
					'success' => false,
					'error'   => $e->getMessage(),
				];
			}
		}

		return $results;
	}
}
