<?php
/** Read-only ability for the bounded ACPT Lite WooCommerce product-data contract. */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** @return array<string,mixed> */
function wpagent_ability_list_acpt_woocommerce_product_data(): array {
	return array(
		'label'       => __( 'ACPT-Lite-WooCommerce-Product-Data auflisten', 'wp-agent-companion' ),
		'description' => __( 'Liest begrenzt und sortiert nur vorhandene ACPT-Lite-2.0.11-Product-Data-Gruppen, deren vollständige Konfiguration aus Text-, Number- und Select-Feldern besteht.', 'wp-agent-companion' ),
		'category'    => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'search' => array( 'type' => 'string', 'maxLength' => 100 ),
				'page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 50 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 50 ),
			),
			'additionalProperties' => false,
		),
		'output_schema' => wpagent_acpt_product_data_list_schema(),
		'execute_callback' => 'wpagent_exec_list_acpt_woocommerce_product_data',
		'permission_callback' => 'wpagent_perm_acpt_product_data',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed> */
function wpagent_acpt_product_data_group_schema(): array {
	return array(
		'type' => 'object',
		'properties' => array(
			'id' => array( 'type' => 'string', 'pattern' => '^[a-f0-9-]{36}$' ),
			'name' => array( 'type' => 'string' ),
			'show_in_ui' => array( 'type' => 'boolean' ),
			'visibility' => array( 'type' => 'array', 'maxItems' => 6, 'uniqueItems' => true, 'items' => array( 'type' => 'string', 'enum' => array( 'show_if_simple', 'show_if_variable', 'show_if_grouped', 'show_if_external', 'hide_if_virtual', 'hide_if_external' ) ) ),
			'fields' => array(
				'type' => 'array', 'maxItems' => WPAGENT_ACPT_PRODUCT_DATA_MAX_FIELDS,
				'items' => array(
					'type' => 'object',
					'properties' => array(
						'id' => array( 'type' => 'string', 'pattern' => '^[a-f0-9-]{36}$' ),
						'name' => array( 'type' => 'string' ), 'type' => array( 'type' => 'string', 'enum' => array( 'Text', 'Number', 'Select' ) ),
						'default_value' => array( 'type' => 'string' ), 'description' => array( 'type' => 'string' ), 'required' => array( 'type' => 'boolean' ), 'sort' => array( 'type' => 'integer' ),
						'options' => array(
							'type' => 'array', 'maxItems' => WPAGENT_ACPT_PRODUCT_DATA_MAX_OPTIONS,
							'items' => array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => 'string', 'pattern' => '^[a-f0-9-]{36}$' ), 'label' => array( 'type' => 'string' ), 'value' => array( 'type' => 'string' ), 'sort' => array( 'type' => 'integer' ) ), 'required' => array( 'id', 'label', 'value', 'sort' ), 'additionalProperties' => false ),
						),
					),
					'required' => array( 'id', 'name', 'type', 'default_value', 'description', 'required', 'sort', 'options' ), 'additionalProperties' => false,
				),
			),
			'provider_version' => array( 'type' => 'string', 'enum' => array( '2.0.11' ) ), 'state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		),
		'required' => array( 'id', 'name', 'show_in_ui', 'visibility', 'fields', 'provider_version', 'state_hash' ), 'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_acpt_product_data_list_schema(): array {
	return array(
		'type' => 'object',
		'properties' => array( 'items' => array( 'type' => 'array', 'maxItems' => 50, 'items' => wpagent_acpt_product_data_group_schema() ), 'total' => array( 'type' => 'integer', 'minimum' => 0 ), 'skipped_unsafe' => array( 'type' => 'integer', 'minimum' => 0 ) ),
		'required' => array( 'items', 'total', 'skipped_unsafe' ), 'additionalProperties' => false,
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_acpt_woocommerce_product_data( $input ) {
	$input = is_array( $input ) ? $input : array();
	$capability = wpagent_acpt_product_data_require_capability();
	if ( is_wp_error( $capability ) ) return $capability;
	$provider = wpagent_acpt_product_data_provider();
	if ( is_wp_error( $provider ) ) return $provider;
	$search = $input['search'] ?? '';
	if ( ! is_string( $search ) || sanitize_text_field( $search ) !== $search ) return new WP_Error( 'wpagent_acpt_product_data_invalid', __( 'Die Suche ist nicht sicher.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	$page = (int) ( $input['page'] ?? 1 );
	$per_page = (int) ( $input['per_page'] ?? 50 );
	if ( $page < 1 || $page > 50 || $per_page < 1 || $per_page > 50 ) return new WP_Error( 'wpagent_acpt_product_data_limit', __( 'Die Seitengröße liegt außerhalb der sicheren Grenze.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	$tables = wpagent_acpt_product_data_tables( $provider );
	if ( is_wp_error( $tables ) ) return $tables;
	global $wpdb;
	$wpdb->last_error = '';
	$rows = $wpdb->get_results( "SELECT id, product_data_name FROM `{$tables['group']}` ORDER BY product_data_name ASC, id ASC LIMIT 51", ARRAY_A );
	if ( '' !== $wpdb->last_error || ! is_array( $rows ) || count( $rows ) > WPAGENT_ACPT_PRODUCT_DATA_MAX_GROUPS ) return new WP_Error( 'wpagent_acpt_product_data_limit', __( 'Zu viele ACPT-Lite-Product-Data-Gruppen für den sicheren Lesevertrag.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	$all = array();
	$skipped = 0;
	foreach ( $rows as $row ) {
		if ( ! is_array( $row ) || ! wpagent_acpt_product_data_uuid( $row['id'] ?? null ) ) { ++$skipped; continue; }
		$raw = wpagent_acpt_product_data_raw( $row['id'], $provider );
		if ( is_wp_error( $raw ) ) { ++$skipped; continue; }
		$public = wpagent_acpt_product_data_public( $raw );
		if ( is_wp_error( $public ) ) { ++$skipped; continue; }
		$group = array_merge( $public, array( 'provider_version' => $provider['version'], 'state_hash' => wpagent_acpt_product_data_hash( $raw ) ) );
		if ( '' !== $search && false === stripos( $group['name'], $search ) ) continue;
		$all[] = $group;
	}
	$offset = ( $page - 1 ) * $per_page;
	return array( 'items' => array_slice( $all, $offset, $per_page ), 'total' => count( $all ), 'skipped_unsafe' => $skipped );
}
