<?php
/**
 * Ability: wp-agent/get-product
 *
 * Read-only. Liest die Kerndaten eines WooCommerce-Produkts ausschließlich
 * über die WC_Product-Getter (wc_get_product()), nie über rohes postmeta,
 * analog zu update-product.php.
 *
 * @package WPAgentCompanion
 */

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

function wpagent_ability_get_product(): array {
	return array(
		'label'               => __( 'Produkt lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest Produktdaten einschließlich Preise, Lager, Medien, Versand, Abmessungen, Taxonomien und Attribute über die WC_Product-Getter.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'       => 'object',
			'properties' => array(
				'product_id' => array( 'type' => 'integer' ),
			),
			'required'   => array( 'product_id' ),
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'product_id'        => array( 'type' => 'integer' ),
				'type'              => array( 'type' => 'string' ),
				'status'            => array( 'type' => 'string' ),
				'name'              => array( 'type' => 'string' ),
				'sku'               => array( 'type' => 'string' ),
				'regular_price'     => array( 'type' => 'string' ),
				'sale_price'        => array( 'type' => 'string' ),
				'price'             => array( 'type' => 'string' ),
				'stock_quantity'    => array(
					'type'        => array( 'integer', 'null' ),
					'description' => __( 'Ganzzahl oder null (kein Lagerbestand geführt).', 'wp-agent-companion' ),
				),
				'manage_stock'      => array( 'type' => 'boolean' ),
				'stock_status'      => array( 'type' => 'string' ),
				'short_description' => array( 'type' => 'string' ),
				'description'       => array( 'type' => 'string' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_get_product',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => true,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * @param mixed $input
 * @return array|WP_Error
 */
function wpagent_exec_get_product( $input ) {
	$input      = is_array( $input ) ? $input : array();
	$product_id = (int) ( $input['product_id'] ?? 0 );
	$product    = wpagent_get_editable_product( $product_id );
	if ( is_wp_error( $product ) ) {
		return $product;
	}
	return wpagent_wc_product_payload( $product );
}
