<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class ListBrandsAbility {

	const ABILITY_NAME = 'aieo/list-brands';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'List brands', 'ai-eshop-optimizer' ),
				'description'         => __( 'List all `product_brand` taxonomy terms with product counts, in-stock counts, and lifetime sales (from `wp_aieo_core_brand_vitals`).', '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(
				'limit' => array(
					'type'    => 'integer',
					'minimum' => 1,
					'maximum' => 500,
					'default' => 100,
				),
				'order' => array(
					'type'    => 'string',
					'enum'    => array( 'sales_desc', 'products_desc', 'newest' ),
					'default' => 'sales_desc',
				),
			),
		);
	}

	public static function execute( $input ) {
		$input = is_array( $input ) ? $input : array();
		$limit = isset( $input['limit'] ) ? max( 1, min( 500, (int) $input['limit'] ) ) : 100;
		$order = isset( $input['order'] ) ? sanitize_key( (string) $input['order'] ) : 'sales_desc';
		if ( ! class_exists( 'AIEO_Core_Brand_Vitals' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO_Core_Brand_Vitals not loaded.', 'ai-eshop-optimizer' ) );
		}
		$cbv = \AIEO_Core_Brand_Vitals::instance();
		switch ( $order ) {
			case 'newest':         $brands = $cbv->get_newest_product( $limit ); break;
			case 'products_desc':
			case 'sales_desc':
			default:               $brands = $cbv->get_top( $limit ); break;
		}
		return array(
			'order'  => $order,
			'limit'  => $limit,
			'brands' => $brands,
		);
	}
}
