<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class BlogEngagementLeaderboardAbility {

	const ABILITY_NAME = 'aieo/blog-engagement-leaderboard';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Blog engagement leaderboard', 'ai-eshop-optimizer' ),
				'description'         => __( 'Top blog posts (and other non-product / non-archive pages) by total views, distinct visitors, avg time-on-page, and avg scroll-depth in the period. Sourced from wp_aieo_sessions page_view rows.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => self::input_schema(),
				'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' );
	}

	private static function input_schema() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'period' => array(
					'type'    => 'string',
					'default' => 'last_30_days',
					'enum'    => PeriodHelper::ALLOWED,
				),
				'limit'  => array(
					'type'    => 'integer',
					'minimum' => 1,
					'maximum' => 100,
					'default' => 20,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input  = is_array( $input ) ? $input : array();
		$period = isset( $input['period'] ) ? (string) $input['period'] : 'last_30_days';
		$limit  = isset( $input['limit'] ) ? (int) $input['limit'] : 20;
		if ( ! class_exists( 'AIEO_Session_Attribution_Bridge' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO_Session_Attribution_Bridge not loaded.', 'ai-eshop-optimizer' ) );
		}
		return \AIEO_Session_Attribution_Bridge::get_blog_engagement_leaderboard( $period, $limit );
	}
}
