<?php

namespace EasyLinkAutomations\Actions\Mailchimp;

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

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

/**
 * Action that retrieves a member from a Mailchimp list.
 *
 * Migrated from n8n: Mailchimp (resource: member, operation: get)
 * Uses Mailchimp Marketing API v3.0.
 */
final class GetMemberAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'mailchimp/get_member';
    }

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

    public static function getDescription(): string
    {
        return __('Get a subscriber from a Mailchimp audience list', 'easylink-automations');
    }

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

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


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

    public static function getConfigFields(): array
    {
        return [
            'list_id' => [
                'label'         => 'Audience List',
                'type'          => 'remote_select',
                'required'      => true,
                'placeholder'   => 'Select a list...',
                'remote_source' => 'mailchimp/lists',
                'depends_on'    => ['connection_id'],
                'options_key'   => 'lists',
            ],
            'email' => [
                'label'       => 'Email Address',
                'type'        => 'email',
                'required'    => true,
                'placeholder' => 'name@email.com',
                'description' => "Member's email address",
            ],
        ];
    }

    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 Mailchimp connection found or token expired'];
        }

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

        $apiBase = $this->getApiBase($token);
        if (!$apiBase) {
            return ['success' => false, 'message' => 'Failed to determine Mailchimp API datacenter'];
        }

        $listId     = $mapped['list_id'];
        $email      = $mapped['email'];
        $emailHash  = md5(strtolower(trim($email)));

        $url = "{$apiBase}/lists/{$listId}/members/{$emailHash}";
        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
            ],
            '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
                ? 'Member retrieved successfully'
                : 'Failed to get member (HTTP ' . $statusCode . '): ' . ($responseBody['detail'] ?? 'Unknown error'),
            'data' => $responseBody ?? [],
        ];
    }

    private function getApiBase(string $token): ?string
    {
        $response = wp_remote_get('https://login.mailchimp.com/oauth2/metadata', [
            'headers' => ['Authorization' => 'OAuth ' . $token],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            return null;
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (!empty($body['api_endpoint'])) {
            return rtrim($body['api_endpoint'], '/') . '/3.0';
        }

        return !empty($body['dc'])
            ? 'https://' . $body['dc'] . '.api.mailchimp.com/3.0'
            : null;
    }
}
