<?php
/**
 * Add Tag Action Definition
 *
 * @package Sequensy\Integrations\Kit
 * @since 1.0.0
 */

declare(strict_types=1);

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

use Sequensy\Integrations\Kit\Helpers\SubscriberHelper;

return array(
	'type'            => 'add_tag',
	'label'           => __( 'Add Tag', 'sequensy' ),
	'description'     => __( 'Add a tag to a subscriber.', 'sequensy' ),
	'category'        => 'tag',
	'required_fields' => array( 'email_address', 'tag_id' ),
	'schema'          => array(
		array(
			'name'        => 'email_address',
			'type'        => 'string',
			'label'       => __( 'Email Address', 'sequensy' ),
			'description' => __( 'Subscriber must already exist', 'sequensy' ),
			'required'    => true,
			'order'       => 1,
			'width'       => '1/2',
		),
		array(
			'name'        => 'tag_id',
			'type'        => 'select',
			'label'       => __( 'Tag', 'sequensy' ),
			'required'    => true,
			'dynamic'     => true,
			'endpoint'    => '/integrations/kit/connections/{connection_id}/tags',
			'depends_on'  => 'connection_id',
			'value_field' => 'id',
			'label_field' => 'name',
			'order'       => 2,
			'width'       => '1/2',
		),
	),
	'output_fields'   => array(
		array(
			'name'        => 'subscriber_id',
			'type'        => 'string',
			'description' => __( 'Subscriber ID', 'sequensy' ),
			'example'     => '12345',
		),
		array(
			'name'        => 'tag_id',
			'type'        => 'string',
			'description' => __( 'Tag ID', 'sequensy' ),
			'example'     => '67890',
		),
		array(
			'name'        => 'tag_name',
			'type'        => 'string',
			'description' => __( 'Tag name', 'sequensy' ),
			'example'     => 'Premium',
		),
	),
	'handler'         => function ( array $config, array $context ): array {
		$email = sanitize_email( $config['email_address'] );

		if ( ! is_email( $email ) ) {
			throw new \RuntimeException(
				sprintf(
					/* translators: %s: email address */
					esc_html__( 'Invalid email address: %s', 'sequensy' ),
					esc_attr( $config['email_address'] )
				)
			);
		}

		$tag_id = absint( $config['tag_id'] );

		if ( 0 === $tag_id ) {
			throw new \RuntimeException(
				esc_html__( 'A valid tag is required.', 'sequensy' )
			);
		}

		$subscriber_id = SubscriberHelper::resolve_subscriber_id( $email );

		$result = sequensy_api( 'kit' )->add_tag( $subscriber_id, $tag_id );

		if ( is_wp_error( $result ) ) {
			throw new \RuntimeException( esc_html( $result->get_error_message() ) );
		}

		return array(
			'subscriber_id' => (string) $subscriber_id,
			'tag_id'        => (string) $tag_id,
			'tag_name'      => $result['data']['tag']['name'] ?? '',
		);
	},
);
