<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class DataForSEOStatusAbility {

	const ABILITY_NAME = 'aieo/dataforseo-status';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'DataForSEO connection status', 'ai-eshop-optimizer' ),
				'description'         => __( 'Whether this site is connected to DataForSEO (SEO → General), the account login, current balance in USD and API rate limits. Free endpoint — costs nothing to call. Use before proposing any billed keyword/SERP data pull.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array( 'type' => 'object', 'properties' => (object) array() ),
				'output_schema'       => array( 'type' => 'object' ),
				'execute_callback'    => array( __CLASS__, 'execute' ),
				'permission_callback' => array( __CLASS__, 'permission_check' ),
				'meta'                => array(
					'annotations'  => array(
						'readonly'   => true,
						'idempotent' => true,
					),
					'show_in_rest' => true,
				),
			)
		);
	}

	public static function permission_check( $input = null ) {
		unset( $input );
		return current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' );
	}

	public static function execute( $input ) {
		unset( $input );
		if ( ! class_exists( 'AIEO_DataForSEO' ) ) {
			require_once AIEO_DIR . 'includes/seo/class-aieo-dataforseo.php';
		}
		if ( ! \AIEO_DataForSEO::is_connected() ) {
			return array(
				'connected' => false,
				'hint'      => __( 'Connect this site in SEO → General → DataForSEO connection.', 'ai-eshop-optimizer' ),
			);
		}
		$test = \AIEO_DataForSEO::test_connection();
		if ( is_wp_error( $test ) ) {
			return array(
				'connected' => true,
				'healthy'   => false,
				'error'     => $test->get_error_message(),
			);
		}
		return array(
			'connected' => true,
			'healthy'   => true,
			'login'     => $test['login'],
			'balance'   => $test['balance'],
			'currency'  => $test['currency'],
			'limits'    => $test['limits'],
		);
	}
}
