<?php

namespace EasyLinkAutomations\Actions\ActiveCampaign;

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

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

/**
 * Action that adds a tag to a contact in ActiveCampaign.
 */
final class AddContactTagAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'active_campaign/add_contact_tag';
    }

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

    public static function getDescription(): string
    {
        return __('Add a tag to a contact in ActiveCampaign', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'active-campaign';
    }


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

    public static function getConfigFields(): array
    {
        return [
            'contact_id' => [
                'label'         => 'Contact',
                'type'          => 'remote_select',
                'required'      => true,
                'remote_source' => 'active-campaign/contacts',
                'depends_on'    => ['connection_id'],
                'options_key'   => 'contacts',
            ],
            'tag_id' => [
                'label'         => 'Tag',
                'type'          => 'remote_select',
                'required'      => true,
                'remote_source' => 'active-campaign/tags',
                'depends_on'    => ['connection_id'],
                'options_key'   => 'tags',
            ],
        ];
    }

    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);
        $connection = Connection::find($connectionId);
        if (!$connection) {
            return ['success' => false, 'message' => 'Connection not found'];
        }

        $creds  = Connection::getCredentials($connection);
        $apiUrl = rtrim($creds['api_url'] ?? '', '/');
        $apiKey = $creds['api_key'] ?? '';
        if (empty($apiUrl) || empty($apiKey)) {
            return ['success' => false, 'message' => 'Invalid ActiveCampaign credentials'];
        }

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

        $response = wp_remote_request("{$apiUrl}/api/3/contactTags", [
            'method'  => 'POST',
            'headers' => [
                'Content-Type' => 'application/json',
                'Api-Token'    => $apiKey,
            ],
            'body'    => wp_json_encode([
                'contactTag' => [
                    'contact' => $mapped['contact_id'],
                    'tag'     => $mapped['tag_id'],
                ],
            ]),
            '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 ? 'Tag added to contact successfully' : 'Failed (HTTP ' . $statusCode . ')',
            'data'    => $responseBody['contactTag'] ?? [],
        ];
    }
}
