<?php

namespace EasyLinkAutomations\Actions\Brevo;

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

use EasyLinkAutomations\Actions\BaseAction;
use EasyLinkAutomations\Models\Connection;

/**
 * Action that creates a new contact in Brevo.
 *
 * Uses Brevo Contacts API v3.0.
 */
final class CreateContactAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'brevo/create_contact';
    }

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

    public static function getDescription(): string
    {
        return __('Create a new contact in Brevo', 'easylink-automations');
    }

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

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


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

    public static function getConfigFields(): array
    {
        return [
            'attributes' => [
                'label'            => 'Contact Fields',
                'type'             => 'field_mapping',
                'required'         => true,
                'remote_source'    => 'brevo/contact-attributes',
                'depends_on'       => ['connection_id'],
                'options_key'      => 'columns',
                'supports_mapping' => true,
            ],
            'list_ids' => [
                'label'         => 'Lists',
                'type'          => 'remote_multi_select',
                'required'      => false,
                'placeholder'   => 'Select lists to add the contact to...',
                'remote_source' => 'brevo/lists',
                'depends_on'    => ['connection_id'],
                'options_key'   => 'lists',
            ],
        ];
    }

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

        $connectionId = (int) ($config['connection_id'] ?? 0);
        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return ['success' => false, 'message' => 'No valid Brevo connection found or token expired'];
        }

        $mapped = $this->mapConfig($config, $triggerData);

        $fields = BrevoRequestHelper::parseFieldMapping($mapped['attributes'] ?? '{}');

        // Extract email (required field from field_mapping)
        $email = $fields['EMAIL'] ?? '';
        if (empty($email)) {
            return ['success' => false, 'message' => 'Email is required'];
        }

        $body = [
            'email' => $email,
        ];

        // Remaining fields are contact attributes
        unset($fields['EMAIL']);
        if (!empty($fields)) {
            // Filter out empty values
            $attributes = array_filter($fields, function ($value) {
                return $value !== '' && $value !== null;
            });
            if (!empty($attributes)) {
                $body['attributes'] = $attributes;
            }
        }

        // Add list IDs from multi-select
        $listIds = BrevoRequestHelper::parseIdList($mapped['list_ids'] ?? []);
        if (!empty($listIds)) {
            $body['listIds'] = $listIds;
        }

        $url = BrevoRequestHelper::url('contacts');
        $response = wp_remote_request($url, [
            'method'  => 'POST',
            'headers' => BrevoRequestHelper::headers($token, true),
            'body'    => wp_json_encode($body),
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'message' => 'Request failed: ' . $response->get_error_message()];
        }

        $statusCode   = wp_remote_retrieve_response_code($response);
        $responseBody = json_decode(wp_remote_retrieve_body($response), true);
        $success      = $statusCode >= 200 && $statusCode < 300;

        return [
            'success' => $success,
            'message' => $success
                ? 'Contact created successfully'
                : BrevoRequestHelper::failureMessage($statusCode, $responseBody),
            'data' => $responseBody ?? [],
        ];
    }
}
