<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class AbandonedCartTriageAbility {

	const ABILITY_NAME = 'aieo/abandoned-cart-triage';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Abandoned cart triage', 'ai-eshop-optimizer' ),
				'description'         => __( 'Sessions with ≥1 cart-add and NO purchase-complete event, optionally filtered by minimum estimated cart value. Returns the pseudonym Customer #N, the top-5 products by quantity in that cart, the est_value, and last activity timestamp. Real names and emails NEVER leave the server.', '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_7_days',
					'enum'    => PeriodHelper::ALLOWED,
				),
				'min_value' => array(
					'type'    => 'number',
					'minimum' => 0,
					'default' => 0,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input     = is_array( $input ) ? $input : array();
		$period    = isset( $input['period'] ) ? (string) $input['period'] : 'last_7_days';
		$min_value = isset( $input['min_value'] ) ? (float) $input['min_value'] : 0.0;
		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_abandoned_carts( $period, $min_value );
	}
}
