<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class BlogToProductConversionAbility {

	const ABILITY_NAME = 'aieo/blog-to-product-conversion';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Blog → product conversion', 'ai-eshop-optimizer' ),
				'description'         => __( 'For the top blog pages in the period, count visitors → product viewers (next click into a product) → cart-adders. Prefers source=blog_post attribution; falls back to same-session attribution if blog-post source rows are absent.', '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_blog_to_product_conversion( $period );
	}
}
