<?php
/**
 * Provider-status REST controller.
 *
 * @package Carticy\Conversions\Rest
 */

declare(strict_types=1);

namespace Carticy\Conversions\Rest;

use Carticy\Conversions\Client\ClientTrackingSettings;

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

/**
 * Reports which providers are ACTUALLY available - client providers from the
 * stored config, and server-side availability from the premium bridge - so the
 * frontend reflects shipped code, never a feature the build cannot run.
 */
final class ProviderStatusController extends AbstractRestController {

	/**
	 * Premium server bridge.
	 *
	 * @var PremiumServerBridge
	 */
	private PremiumServerBridge $server;

	/**
	 * Constructor.
	 *
	 * @param PremiumServerBridge $server Premium server bridge.
	 */
	public function __construct( PremiumServerBridge $server ) {
		$this->server = $server;
	}

	/**
	 * Declared routes.
	 *
	 * @return array<int, array<string, mixed>>
	 */
	public function routes(): array {
		return array(
			array(
				'methods'  => 'GET',
				'route'    => '/provider-status',
				'callback' => array( $this, 'get_status' ),
			),
		);
	}

	/**
	 * Report client + server provider availability.
	 *
	 * @return \WP_REST_Response
	 */
	public function get_status(): \WP_REST_Response {
		$client = ClientTrackingSettings::from_options();

		$client_status = array();
		foreach ( array( 'ga4', 'google_ads', 'meta' ) as $provider ) {
			$config                     = $client->provider_config( $provider );
			$client_status[ $provider ] = array(
				'configured' => $client->provider_enabled( $provider ),
				'mode'       => (string) ( $config['mode'] ?? 'off' ),
			);
		}

		$available = $this->server->available();

		return $this->ok(
			array(
				'client' => $client_status,
				'server' => array(
					'available' => $available,
					'reason'    => $available ? 'licensed' : 'pro_feature',
				),
				'plan'   => array(
					'isPremium' => function_exists( 'carticy_conversions_can_use_premium' ) && carticy_conversions_can_use_premium(),
				),
			)
		);
	}
}
