<?php

namespace EasyLinkAutomations\Actions\Slack;

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

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

/**
 * Action that sends a message to a Slack channel or user.
 *
 * Uses Slack Web API: chat.postMessage
 */
final class SendMessageAction extends BaseAction
{
    public static function getSlug(): string
    {
        return 'slack/send_message';
    }

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

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

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

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


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

    public static function getConfigFields(): array
    {
        return [
            'channel_id' => [
                'label'         => 'Channel',
                'type'          => 'remote_select',
                'required'      => true,
                'placeholder'   => 'Select a channel...',
                'remote_source' => 'slack/channels',
                'depends_on'    => ['connection_id'],
                'options_key'   => 'channels',
            ],
            'text' => [
                'label'            => 'Message Text',
                'type'             => 'textarea',
                'required'         => true,
                'supports_mapping' => true,
                'placeholder'      => 'Hello from EasyLink Automations!',
            ],
            'as_user' => [
                'label'       => 'Send as User',
                'type'        => 'toggle',
                'required'    => false,
                'default'     => false,
                'description' => 'Send as the authenticated user instead of as a bot',
            ],
            'thread_ts' => [
                'label'            => 'Thread Timestamp',
                'type'             => 'text',
                'required'         => false,
                'supports_mapping' => true,
                'placeholder'      => 'Thread timestamp to reply to',
                'description'      => 'Message timestamp to reply to as a thread',
            ],
            'unfurl_links' => [
                'label'       => 'Unfurl Links',
                'type'        => 'toggle',
                'required'    => false,
                'default'     => true,
                'description' => 'Enable unfurling of primarily text-based content',
            ],
        ];
    }

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

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

        $body = [
            'channel' => $mapped['channel_id'],
            'text'    => $mapped['text'],
        ];

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

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

        if (isset($mapped['unfurl_links'])) {
            $body['unfurl_links'] = (bool) $mapped['unfurl_links'];
        }

        $url = 'https://slack.com/api/chat.postMessage';
        $response = wp_remote_request($url, [
            'method'  => 'POST',
            'headers' => [
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $token,
            ],
            'body'    => wp_json_encode($body),
            'timeout' => 30,
        ]);

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

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $success = !empty($body['ok']);

        return [
            'success' => $success,
            'message' => $success
                ? 'Message sent successfully'
                : 'Failed to send message: ' . ($body['error'] ?? 'Unknown error'),
            'data' => $success
                ? ['ts' => $body['ts'], 'channel' => $body['channel']]
                : [],
        ];
    }
}
