<?php
/**
 * SEO provider registry.
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Stores and resolves SEO provider integrations.
 */
class SmartyPress_AI_SEO_Provider_Registry {

	/**
	 * Registered integrations.
	 *
	 * @var SmartyPress_AI_SEO_Provider_Integration[]
	 */
	private $providers = array();

	/**
	 * Register an integration.
	 *
	 * @param SmartyPress_AI_SEO_Provider_Integration $provider Provider integration.
	 * @return void
	 */
	public function register( $provider ) {
		if ( ! $provider instanceof SmartyPress_AI_SEO_Provider_Integration ) {
			return;
		}

		$this->providers[ $provider->get_id() ] = $provider;
	}

	/**
	 * Get all registered providers.
	 *
	 * @return SmartyPress_AI_SEO_Provider_Integration[]
	 */
	public function all() {
		return $this->providers;
	}

	/**
	 * Get a provider by ID.
	 *
	 * @param string $provider_id Provider ID.
	 * @return SmartyPress_AI_SEO_Provider_Integration|null
	 */
	public function get( $provider_id ) {
		$provider_id = sanitize_key( $provider_id );

		return isset( $this->providers[ $provider_id ] ) ? $this->providers[ $provider_id ] : null;
	}

	/**
	 * Get the first available provider for a post type.
	 *
	 * @param string $post_type Post type.
	 * @return SmartyPress_AI_SEO_Provider_Integration|null
	 */
	public function get_active_provider( $post_type = '' ) {
		foreach ( $this->providers as $provider ) {
			if ( ! $provider->is_available() ) {
				continue;
			}

			if ( '' !== $post_type && ! $provider->supports_post_type( $post_type ) ) {
				continue;
			}

			return $provider;
		}

		return null;
	}

	/**
	 * Get provider metadata for scripts.
	 *
	 * @param string $post_type Post type.
	 * @return array
	 */
	public function get_script_data( $post_type = '' ) {
		$data = array();

		foreach ( $this->providers as $provider ) {
			$data[] = array(
				'id'           => $provider->get_id(),
				'label'        => $provider->get_label(),
				'available'    => $provider->is_available(),
				'supportsPost' => '' === $post_type || $provider->supports_post_type( $post_type ),
			);
		}

		return $data;
	}
}
