<?php
/**
 * Remove Subscriber Action Definition
 *
 * @package Sequensy\Integrations\CampaignMonitor
 * @since 1.0.0
 */

declare(strict_types=1);

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

return array(
	'type'            => 'remove_subscriber',
	'label'           => __( 'Remove Subscriber', 'sequensy' ),
	'description'     => __( 'Unsubscribe a subscriber from a Campaign Monitor list.', 'sequensy' ),
	'category'        => 'subscriber',
	'required_fields' => array( 'list_id', 'email' ),
	'schema'          => array(
		array(
			'name'        => 'list_id',
			'type'        => 'select',
			'label'       => __( 'List', 'sequensy' ),
			'description' => __( 'Select a Campaign Monitor list', 'sequensy' ),
			'required'    => true,
			'dynamic'     => true,
			'endpoint'    => '/integrations/campaignmonitor/connections/{connection_id}/lists',
			'depends_on'  => 'connection_id',
			'value_field' => 'id',
			'label_field' => 'name',
			'order'       => 1,
		),
		array(
			'name'        => 'email',
			'type'        => 'string',
			'label'       => __( 'Email', 'sequensy' ),
			'description' => __( 'Subscriber email address', 'sequensy' ),
			'required'    => true,
			'order'       => 2,
		),
	),
	'output_fields'   => array(
		array(
			'name'        => 'email',
			'type'        => 'string',
			'description' => __( 'Email address of the unsubscribed subscriber', 'sequensy' ),
			'example'     => 'subscriber@example.com',
		),
		array(
			'name'        => 'list_id',
			'type'        => 'string',
			'description' => __( 'Campaign Monitor list ID', 'sequensy' ),
			'example'     => 'abc123',
		),
	),
	'handler'         => function ( array $config, array $context ): array {
		$list_id = sanitize_text_field( $config['list_id'] );
		$email   = sanitize_email( $config['email'] );

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

		$result = sequensy_api( 'campaignmonitor' )->unsubscribe( $list_id, $email );

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

		return array(
			'email'   => $email,
			'list_id' => $list_id,
		);
	},
);
