<?php

declare(strict_types=1);

namespace FormConnector\API\Endpoints;

use FormConnector\Integration\Health\HealthPing;
use FormConnector\Integration\CareHQ\Signing;

/**
 * REST endpoint for manually triggering a CareHQ health ping.
 *
 * POST /wp-json/fc/v1/health/ping
 *
 * Allows an admin to re-register this site with CareHQ on demand — useful when
 * the signing secret has been lost (e.g. wp_options cleared) without waiting
 * for the next hourly cron run.
 */
class HealthPingEndpoints {

	private const NAMESPACE = 'fc/v1';

	/**
	 * Register routes.
	 */
	public static function register(): void {
		register_rest_route(self::NAMESPACE, '/health/ping', [
			'methods'             => \WP_REST_Server::CREATABLE,
			'callback'            => [self::class, 'send_ping'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

		register_rest_route(self::NAMESPACE, '/health/ping/status', [
			'methods'             => \WP_REST_Server::READABLE,
			'callback'            => [self::class, 'get_status'],
			'permission_callback' => [self::class, 'permission_check'],
		]);

	}

	/**
	 * Admin-only access.
	 */
	public static function permission_check(): bool {
		return current_user_can('manage_options');
	}

	/**
	 * Trigger a health ping immediately.
	 */
	public static function send_ping(\WP_REST_Request $request): \WP_REST_Response {
		$result = HealthPing::send_ping();

		$has_secret = Signing::get_secret() !== '';

		if ($result['success']) {
			return new \WP_REST_Response([
				'success' => true,
				'message' => __('Site successfully reconnected to CareHQ.', 'form-connector'),
				'data'    => [
					'has_signing_secret' => $has_secret,
					'last_ping'          => get_option(Signing::OPTION_LAST_PING),
					'health_status'      => get_option(Signing::OPTION_HEALTH_STATUS, 'ok'),
					'plugin_update'      => get_option(Signing::OPTION_PLUGIN_UPDATE, null),
					'webhook_url'        => HealthPing::webhook_url(),
				],
			], 200);
		}

		return new \WP_REST_Response([
			'success' => false,
			'message' => $result['message'] ?? __('Health ping failed. Check your API key and try again.', 'form-connector'),
			'data'    => [
				'has_signing_secret' => $has_secret,
				'last_ping'          => get_option(Signing::OPTION_LAST_PING),
				'health_status'      => get_option(Signing::OPTION_HEALTH_STATUS, 'error'),
				'plugin_update'      => get_option(Signing::OPTION_PLUGIN_UPDATE, null),
				'webhook_url'        => HealthPing::webhook_url(),
			],
		], 200); // 200 so the frontend can display the error state without a thrown exception
	}

	/**
	 * Return the current health-ping status without triggering a ping.
	 */
	public static function get_status(\WP_REST_Request $request): \WP_REST_Response {
		$has_secret = Signing::get_secret() !== '';

		return new \WP_REST_Response([
			'success' => true,
			'data'    => [
				'has_signing_secret' => $has_secret,
				'last_ping'          => get_option(Signing::OPTION_LAST_PING),
				'last_sync'          => get_option(Signing::OPTION_LAST_SYNC),
				'health_status'      => get_option(Signing::OPTION_HEALTH_STATUS, 'unknown'),
				'plugin_update'      => get_option(Signing::OPTION_PLUGIN_UPDATE, null),
				'webhook_url'        => HealthPing::webhook_url(),
			],
		], 200);
	}
}
