<?php

namespace EasyLinkAutomations\Actions\Telegram;

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

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

/**
 * Action that sends a text message via Telegram Bot API.
 *
 * Migrated from n8n: Telegram (resource: message, operation: sendMessage)
 * Uses Telegram Bot API: POST https://api.telegram.org/bot{TOKEN}/sendMessage
 */
final class SendMessageAction extends BaseAction
{
    private const API_BASE = 'https://api.telegram.org/bot';

    public static function getSlug(): string
    {
        return 'telegram/send_message';
    }

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

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

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

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


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

    public static function getConfigFields(): array
    {
        return [
            'chat_id' => [
                'label'            => 'Chat ID',
                'type'             => 'text',
                'required'         => true,
                'supports_mapping' => true,
                'placeholder'      => '-1001234567890 or @channelusername',
                'description'      => 'Unique identifier for the target chat, group, or channel (@username supported)',
            ],
            'text' => [
                'label'            => 'Message Text',
                'type'             => 'textarea',
                'required'         => true,
                'supports_mapping' => true,
                'placeholder'      => 'Hello, {{first_name}}!',
                'description'      => 'Text of the message to be sent',
            ],
            'parse_mode' => [
                'label'       => 'Parse Mode',
                'type'        => 'select',
                'required'    => false,
                'placeholder' => 'None (plain text)',
                'options'     => [
                    ['value' => 'HTML', 'label' => 'HTML'],
                    ['value' => 'Markdown', 'label' => 'Markdown (Legacy)'],
                    ['value' => 'MarkdownV2', 'label' => 'MarkdownV2'],
                ],
                'description' => 'How to parse the message text',
            ],
            'disable_notification' => [
                'label'       => 'Disable Notification',
                'type'        => 'toggle',
                'required'    => false,
                'description' => 'Send the message silently (users receive notification with no sound)',
            ],
            'reply_to_message_id' => [
                'label'            => 'Reply To Message ID',
                'type'             => 'text',
                'required'         => false,
                'supports_mapping' => true,
                'placeholder'      => '12345',
                'description'      => 'If the message is a reply, ID of the original message',
            ],
        ];
    }

    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 Telegram connection found'];
        }

        $mapped = $this->mapConfig($config, $triggerData);
        $chatId = trim($mapped['chat_id'] ?? '');
        $text   = trim($mapped['text'] ?? '');

        if (empty($chatId)) {
            return ['success' => false, 'message' => 'Chat ID is required'];
        }
        if (empty($text)) {
            return ['success' => false, 'message' => 'Message text is required'];
        }

        $body = [
            'chat_id' => $chatId,
            'text'    => $text,
        ];

        if (!empty($mapped['parse_mode'])) {
            $body['parse_mode'] = $mapped['parse_mode'];
        }
        if (!empty($mapped['disable_notification'])) {
            $body['disable_notification'] = (bool) $mapped['disable_notification'];
        }
        if (!empty($mapped['reply_to_message_id'])) {
            $body['reply_to_message_id'] = (int) $mapped['reply_to_message_id'];
        }

        $url      = self::API_BASE . $token . '/sendMessage';
        $response = wp_remote_post($url, [
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => wp_json_encode($body),
            '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 && ($responseBody['ok'] ?? false);

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