<?php
/**
 * OmnibusHelper class.
 *
 * Detects and delegates lowest price requests to an active Omnibus provider.
 *
 * @package Ilabs\Firevert\Core\Services\Helper\Integration
 */

declare( strict_types=1 );

namespace Ilabs\Firevert\Core\Services\Helper\Integration;

use Ilabs\Firevert\Core\Integration\Omnibus\OmnibusByIlabsProvider;
use Ilabs\Firevert\Core\Integration\Omnibus\OmnibusByPerfectWpProvider;
use Ilabs\Firevert\Core\Integration\Omnibus\OmnibusByPietrzakProvider;
use Ilabs\Firevert\Core\Integration\Omnibus\OmnibusByPriceHistoryProvider;
use Ilabs\Firevert\Core\Integration\Omnibus\OmnibusByProductPriceHistoryProvider;
use Ilabs\Firevert\Core\Integration\Omnibus\OmnibusProviderInterface;

/**
 * Class OmnibusHelper
 */
final class OmnibusHelper {

	/**
	 * Cached provider instance.
	 *
	 * @var OmnibusProviderInterface|null
	 */
	private static ?OmnibusProviderInterface $provider = null;

	/**
	 * Returns the active Omnibus provider.
	 *
	 * @return OmnibusProviderInterface|null Active provider or null if none detected.
	 */
	public static function get_provider(): ?OmnibusProviderInterface {
		if ( null !== self::$provider ) {
			return self::$provider;
		}

		$providers = array(
			new OmnibusByProductPriceHistoryProvider(),
			new OmnibusByPietrzakProvider(),
			new OmnibusByPriceHistoryProvider(),
			new OmnibusByPerfectWpProvider(),
			new OmnibusByIlabsProvider(),
		);

		foreach ( $providers as $provider ) {
			if ( true === $provider->is_active() ) {
				self::$provider = $provider;
				break;
			}
		}

		return self::$provider;
	}

	/**
	 * Returns the lowest price for a product using the detected provider.
	 *
	 * @param int $product_id WooCommerce product ID.
	 *
	 * @return float|null Lowest price or null if unavailable.
	 */
	public static function get_lowest_price( int $product_id ): ?float {
		$provider = self::get_provider();

		if ( null === $provider ) {
			return null;
		}

		return $provider->get_lowest_price( $product_id );
	}

	/**
	 * Returns the date of the lowest price for a product using the detected provider.
	 *
	 * @param int $product_id WooCommerce product ID.
	 * @return string|null Date in 'Y-m-d' format or null if unavailable.
	 */
	public static function get_lowest_price_date( int $product_id ): ?string {
		$provider = self::get_provider();

		if ( null === $provider ) {
			return null;
		}

		return $provider->get_lowest_price_date( $product_id );
	}

	/**
	 * Returns the number of days since the lowest price date, using the detected provider.
	 *
	 * @param int $product_id WooCommerce product ID.
	 * @return int|null Number of days, or null if unavailable/invalid.
	 */
	public static function get_lowest_price_days_ago( int $product_id ): ?int {
		$provider = self::get_provider();

		if ( null === $provider ) {
			return null;
		}

		return $provider->get_lowest_price_days_ago( $product_id );
	}
}
