<?php

namespace EasyLinkAutomations\Actions\Rapidmail;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Adds a subscriber to a rapidmail recipient list.
 *
 * The activation email is rapidmail's double opt-in mechanism and only fires
 * for recipients created with status "new", so the two settings are driven
 * together from a single toggle that defaults to the compliant path.
 *
 * rapidmail API v3: POST /v1/recipients
 */
final class RecipientCreateAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'rapidmail/recipient_create';
    }

    public static function getName(): string
    {
        return __('Add Subscriber', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Add a subscriber to a rapidmail recipient list', 'easylink-automations');
    }

    public static function getCategory(): string
    {
        return 'rapidmail';
    }

    public static function getIcon(): string
    {
        return 'rapidmail';
    }

    public static function getRequiresConnection(): ?string
    {
        return 'rapidmail';
    }

    public static function getConfigFields(): array
    {
        return [
            'recipientlist_id' => [
                'label'            => 'Recipient List',
                'type'             => 'remote_select',
                'required'         => true,
                'supports_mapping' => true,
                'placeholder'      => 'Select a rapidmail recipient list...',
                'remote_source'    => 'rapidmail/recipientlists',
                'options_key'      => 'recipientlists',
                'depends_on'       => ['connection_id'],
            ],
            'fields' => [
                'label'            => 'Subscriber Fields',
                'type'             => 'field_mapping',
                'required'         => true,
                'remote_source'    => 'rapidmail/recipient-fields',
                'options_key'      => 'columns',
                'depends_on'       => ['connection_id'],
                'supports_mapping' => true,
            ],
            'send_activationmail' => [
                'label'       => 'Send Activation Email',
                'type'        => 'toggle',
                'required'    => false,
                'default'     => true,
                'description' => 'Leave this on to add the subscriber as pending and let rapidmail send its '
                    . 'double opt-in confirmation. Turning it off activates the subscriber immediately, '
                    . 'which is only lawful when you already hold documented consent.',
            ],
            'track_stats' => [
                'label'       => 'Track Statistics',
                'type'        => 'toggle',
                'required'    => false,
                'default'     => true,
                'description' => 'Record open and click statistics for this subscriber.',
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $mapped  = $this->mapConfig($config, $triggerData);
        $missing = $this->validateRequired($mapped);
        if ($missing) {
            return [
                'success' => false,
                'message' => 'Missing required fields after mapping: ' . implode(', ', $missing),
                'data'    => [],
            ];
        }

        $connectionId = (int) ($config['connection_id'] ?? 0);

        $payload = RapidmailRecipientHelper::buildPayload(
            RapidmailRecipientHelper::decodeMapping($mapped['fields'] ?? [])
        );

        $email = (string) ($payload['email'] ?? '');
        if ($email === '') {
            return ['success' => false, 'message' => 'Email is required', 'data' => []];
        }
        if (!is_email($email)) {
            return ['success' => false, 'message' => 'Email is not a valid address: ' . $email, 'data' => []];
        }

        $payload = RapidmailRecipientHelper::normalize($payload);
        $invalid = RapidmailRecipientHelper::validate($payload);
        if ($invalid !== '') {
            return ['success' => false, 'message' => $invalid, 'data' => []];
        }

        $recipientListId = (int) $mapped['recipientlist_id'];
        if ($recipientListId <= 0) {
            return ['success' => false, 'message' => 'Recipient List is required', 'data' => []];
        }

        $payload['recipientlist_id'] = $recipientListId;

        // An activation mail is only sent for recipients in the "new" state,
        // so the status has to follow the toggle for double opt-in to work.
        $sendActivation      = !isset($mapped['send_activationmail']) || !empty($mapped['send_activationmail']);
        $payload['status']   = $sendActivation ? 'new' : 'active';

        return RapidmailRequestHelper::request(
            $connectionId,
            'POST',
            '/recipients',
            $payload,
            [
                'send_activationmail' => RapidmailRequestHelper::yesNo($sendActivation),
                'track_stats'         => RapidmailRequestHelper::yesNo(
                    !isset($mapped['track_stats']) || !empty($mapped['track_stats'])
                ),
            ]
        );
    }
}
