<?php

namespace WeDevs\AppBridge\Core\Notifications;

use Throwable;

class NotificationManager {

	/**
	 * Dispatch the notification through every driver listed in via().
	 *
	 * Driver failures are caught and logged so one transport going down
	 * never blocks delivery on another.
	 *
	 * @param string $option_key Option key whose provider credentials should
	 *                           be used. Defaults to the legacy Pocket Store
	 *                           key — integrations with their own OneSignal
	 *                           config (Vendor App, etc.) must pass their own.
	 *
	 * @return array<string, bool> map of driver name → success flag
	 */
	public function send( Notification $notification, string $option_key = NotificationDriverFactory::DEFAULT_OPTION_KEY ): array {
		$results = [];

		foreach ( $notification->via() as $driver_name ) {
			try {
				$driver = NotificationDriverFactory::make( $driver_name, $option_key );
				$results[ $driver_name ] = $driver->send( $notification );
			} catch ( Throwable $e ) {
				$results[ $driver_name ] = false;

				// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
				error_log(
					sprintf(
						'[AppBridge Notifications] driver "%s" failed: %s',
						$driver_name,
						$e->getMessage()
					)
				);
			}
		}

		return $results;
	}
}
