<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class ListNeedsAbility {

	const ABILITY_NAME = 'aieo/list-needs';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'List product needs', 'ai-eshop-optimizer' ),
				'description'         => __( 'List every `pa_need` taxonomy term with the count of products carrying it. Use this to audit which needs are well-covered vs sparse.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array( 'type' => 'object' ),
				'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' );
	}

	public static function execute( $input = null ) {
		unset( $input );
		$taxonomy = apply_filters( 'aieo_dmm_needs_taxonomy', 'pa_need' );
		if ( ! taxonomy_exists( $taxonomy ) ) {
			return array(
				'taxonomy' => $taxonomy,
				'needs'    => array(),
				'note'     => __( 'pa_need taxonomy not registered on this site.', 'ai-eshop-optimizer' ),
			);
		}

		$terms = get_terms(
			array(
				'taxonomy'   => $taxonomy,
				'hide_empty' => false,
				'orderby'    => 'count',
				'order'      => 'DESC',
			)
		);
		if ( is_wp_error( $terms ) ) {
			return $terms;
		}

		$out = array();
		foreach ( (array) $terms as $t ) {
			$out[] = array(
				'term_id'       => (int) $t->term_id,
				'name'          => (string) $t->name,
				'slug'          => (string) $t->slug,
				'product_count' => (int) $t->count,
				'archive_url'   => get_term_link( $t ),
			);
		}

		return array(
			'taxonomy' => $taxonomy,
			'needs'    => $out,
			'total'    => count( $out ),
		);
	}
}
