<?php

namespace EasyLinkAutomations\Actions\WordPress;

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

use EasyLinkAutomations\Actions\BaseAction;

/**
 * Action that updates user meta.
 */
final class UpdateUserMetaAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'wordpress/update_user_meta';
    }

    public static function getName(): string
    {
        return __('Update User Meta', 'easylink-automations');
    }

    public static function getDescription(): string
    {
        return __('Update or add user metadata', 'easylink-automations');
    }

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

    public static function getIcon(): string
    {
        return 'user-settings';
    }

    public static function getConfigFields(): array
    {
        return [
            'user_id' => [
                'label'            => 'User ID',
                'type'             => 'text',
                'supports_mapping' => true,
                'required'         => true,
                'placeholder'      => '{{user_id}}',
                'description'      => 'Use a placeholder like {{user_id}} from trigger data',
            ],
            'field_mappings' => [
                'label'            => 'User Meta Fields',
                'type'             => 'field_mapping',
                'required'         => true,
                'remote_source'    => 'wordpress/user-meta-fields',
                'options_key'      => 'columns',
                'supports_mapping' => true,
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $userId = (int) $this->mapValue($config['user_id'] ?? '', $triggerData);

        if (!$userId) {
            return [
                'success' => false,
                'message' => 'User ID is required',
            ];
        }

        if (!get_userdata($userId)) {
            return [
                'success' => false,
                'message' => "User not found: {$userId}",
            ];
        }

        $fieldMappings = $this->mapValue($config['field_mappings'] ?? [], $triggerData);
        $updatedFields = [];

        foreach ($fieldMappings as $metaKey => $metaValue) {
            $metaKey = trim((string) $metaKey);
            if ($metaKey === '') {
                continue;
            }

            $result = update_user_meta($userId, $metaKey, $metaValue);
            if ($result === false && get_user_meta($userId, $metaKey, true) !== $metaValue) {
                return [
                    'success' => false,
                    'message' => "Failed to update user meta field: {$metaKey}",
                ];
            }

            $updatedFields[$metaKey] = $metaValue;
        }

        if (empty($updatedFields)) {
            return [
                'success' => false,
                'message' => 'At least one user meta field is required',
            ];
        }

        return [
            'success' => true,
            'message' => 'User meta updated successfully',
            'data'    => [
                'user_id'        => $userId,
                'updated_fields' => $updatedFields,
            ],
        ];
    }
}
