<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class SessionJourneyForAddcartAbility {

	const ABILITY_NAME = 'aieo/session-journey-for-addcart';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Session journey for cart-add', 'ai-eshop-optimizer' ),
				'description'         => __( 'Given a wp_aieo_addcart_events.id, return the ST session journey for that converting session: referrer, landing page, device, all prior product views in the session up to the cart-add, and the scroll-depth + time-on-page recorded for the converting product view.', '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',
			'required'   => array( 'event_id' ),
			'properties' => array(
				'event_id' => array(
					'type'    => 'integer',
					'minimum' => 1,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input    = is_array( $input ) ? $input : array();
		$event_id = isset( $input['event_id'] ) ? (int) $input['event_id'] : 0;
		if ( $event_id <= 0 ) {
			return new \WP_Error( 'aieo_invalid_input', __( 'event_id is required.', 'ai-eshop-optimizer' ) );
		}
		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_session_journey_for_addcart( $event_id );
	}
}
