<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class CartRemovalAnalysisAbility {

	const ABILITY_NAME = 'aieo/cart-removal-analysis';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Cart-removal analysis', 'ai-eshop-optimizer' ),
				'description'         => __( 'Products most often added then removed within the same session. Joins wp_aieo_addcart_events with wp_aieo_sessions remove_from_cart events by session_id × product_id. Returns top 50 by remove rate — buyers-remorse candidates.', '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,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input  = is_array( $input ) ? $input : array();
		$period = isset( $input['period'] ) ? (string) $input['period'] : 'last_30_days';
		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_cart_removal_patterns( $period );
	}
}
