<?php
/**
 * Remove Tag Action
 *
 * @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'            => 'remove_tag',
	'label'           => __( 'Remove Tag', 'sequensy' ),
	'description'     => __( 'Remove a tag from 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' => __( 'Kit subscriber ID', 'sequensy' ),
			'example'     => '12345',
		),
		array(
			'name'        => 'tag_id',
			'type'        => 'string',
			'description' => __( 'Tag ID that was removed', 'sequensy' ),
			'example'     => '67890',
		),
	),
	'handler'         => function ( array $config, array $context ): array {
		$email  = sanitize_email( $config['email_address'] );
		$tag_id = absint( $config['tag_id'] );

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

		if ( ! $tag_id ) {
			throw new \RuntimeException( esc_html__( 'Tag ID is required.', 'sequensy' ) );
		}

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

		$result = sequensy_api( 'kit' )->remove_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,
		);
	},
);
