<?php
/**
 * Create Post Meta Tool.
 *
 * Create a new meta key/value pair on a post, page, or custom post type.
 * Unlike update_post_meta, this allows adding multiple values for the same key.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://maximum.software/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Create_Post_Meta_Tool class.
 */
class Create_Post_Meta_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'create_post_meta';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Create Post/Page Meta', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new meta key/value pair on a post, page, or custom post type. Can add multiple values for the same key unless unique is set to true.';
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'post_id'    => array(
					'type'        => 'integer',
					'description' => 'The ID of the post to add meta to.',
				),
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for tool parameter, not a database query.
				'meta_key'   => array(
					'type'        => 'string',
					'description' => 'The meta key to add.',
				),
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Array key for tool parameter, not a database query.
				'meta_value' => array(
					'description' => 'The meta value to add. Can be a string, number, boolean, array, object, or null.',
					'anyOf'       => array(
						array( 'type' => 'string' ),
						array( 'type' => 'number' ),
						array( 'type' => 'integer' ),
						array( 'type' => 'boolean' ),
						array( 'type' => 'object' ),
						array(
							'type'  => 'array',
							'items' => array(),
						),
						array( 'type' => 'null' ),
					),
				),
				'unique'     => array(
					'type'        => 'boolean',
					'description' => 'If true, will not add if the meta key already exists. Default: false.',
					'default'     => false,
				),
			),
			'required'   => array( 'post_id', 'meta_key', 'meta_value' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		$post_id    = (int) $args['post_id'];
		$meta_key   = trim( $args['meta_key'] );
		$meta_value = $args['meta_value'];
		$unique     = isset( $args['unique'] ) ? (bool) $args['unique'] : false;

		if ( '' === $meta_key ) {
			return $this->error_response( 'Meta key cannot be empty' );
		}

		$post = get_post( $post_id );

		if ( ! $post ) {
			return $this->error_response( 'Post not found', array( 'post_id' => $post_id ) );
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return $this->error_response( 'You do not have permission to edit this post' );
		}

		$result = add_post_meta( $post_id, $meta_key, $meta_value, $unique );

		if ( false === $result ) {
			if ( $unique ) {
				return $this->error_response(
					'Meta key already exists on this post (unique constraint)',
					array(
						'post_id'  => $post_id,
						// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for response data, not a database query.
						'meta_key' => $meta_key,
					)
				);
			}
			return $this->error_response(
				'Failed to create post meta',
				array(
					'post_id'  => $post_id,
					// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for response data, not a database query.
					'meta_key' => $meta_key,
				)
			);
		}

		return $this->success_response(
			'Post meta created successfully',
			array(
				'post_id'   => $post_id,
				'post_type' => $post->post_type,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Array key for response data, not a database query.
				'meta_key'  => $meta_key,
				'meta_id'   => $result,
				'value'     => $meta_value,
				'unique'    => $unique,
			)
		);
	}
}
