<?php

namespace EasyLinkAutomations\Actions\Discord;

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

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

/**
 * Sends a message to a Discord channel.
 *
 * Migrated from n8n: Discord (resource: message, operation: send)
 * API: POST https://discord.com/api/v10/channels/{channelId}/messages
 */
final class SendMessageAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'discord/send_message';
    }

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

    public static function getDescription(): string
    {
        return __('Send a message to a Discord channel', 'easylink-automations');
    }

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

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


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

    public static function getConfigFields(): array
    {
        return [
            'guild_id' => [
                'label'            => 'Server (Guild) ID',
                'type'             => 'remote_select',
                'required'         => true,
                'remote_source'    => 'discord/guilds',
                'depends_on'       => ['connection_id'],
                'options_key'      => 'guilds',
                'supports_mapping' => false,
                'placeholder'      => 'Select a server',
            ],
            'channel_id' => [
                'label'            => 'Channel',
                'type'             => 'remote_select',
                'required'         => true,
                'remote_source'    => 'discord/text-channels',
                'depends_on'       => ['connection_id', 'guild_id'],
                'options_key'      => 'channels',
                'supports_mapping' => false,
                'placeholder'      => 'Select a channel',
            ],
            'content' => [
                'label'            => 'Message Content',
                'type'             => 'textarea',
                'required'         => false,
                'supports_mapping' => true,
                'placeholder'      => 'Hello, {{first_name}}!',
                'description'      => 'The message text (max 2000 characters). Required if no embed is provided.',
            ],
            'tts' => [
                'label'       => 'Text-to-Speech',
                'type'        => 'toggle',
                'required'    => false,
                'description' => 'Send the message as a text-to-speech message',
            ],
        ];
    }

    public function execute(array $triggerData, array $config): array
    {
        $connectionId = (int) ($config['connection_id'] ?? 0);
        $authHeaders  = Connection::getAuthHeaders($connectionId);
        if (empty($authHeaders)) {
            return ['success' => false, 'message' => 'No valid Discord connection found'];
        }

        $mapped    = $this->mapConfig($config, $triggerData);
        $channelId = trim($mapped['channel_id'] ?? '');
        $content   = trim($mapped['content'] ?? '');

        if (empty($channelId)) {
            return ['success' => false, 'message' => 'Channel ID is required'];
        }
        if (empty($content)) {
            return ['success' => false, 'message' => 'Message content is required'];
        }

        $body = ['content' => $content];

        if (!empty($mapped['tts'])) {
            $body['tts'] = (bool) $mapped['tts'];
        }

        $url      = DiscordRequestHelper::url(DiscordRequestHelper::idPath('channels', $channelId, 'messages'));
        $response = wp_remote_post($url, [
            'headers' => DiscordRequestHelper::jsonHeaders($authHeaders),
            'body'    => wp_json_encode($body),
            'timeout' => 30,
        ]);

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

        $code         = wp_remote_retrieve_response_code($response);
        $responseBody = DiscordRequestHelper::responseBody($response);
        $success      = $code >= 200 && $code < 300;

        return [
            'success' => $success,
            'message' => $success
                ? 'Message sent successfully'
                : 'Failed to send message: ' . DiscordRequestHelper::failureMessage($code, $responseBody),
            'data'    => $success ? $responseBody : [],
        ];
    }
}
