<?php
/**
 * Handles Telegram notifications.
 *
 * @package StockGuardianPro
 */

declare(strict_types=1);

namespace StockGuardianPro\LowStock\Services;

use StockGuardianPro\LowStock\Plugin;

\defined('ABSPATH') || exit;

final class TelegramService implements ServiceInterface
{
    private Plugin $plugin;

    private ?string $last_error = null;

    public function __construct(Plugin $plugin)
    {
        $this->plugin = $plugin;
    }

    public function register(): void
    {
    }

    public function is_enabled(): bool
    {
        $enabled    = (bool) get_option('woolsn_telegram_enabled', false);
        $bot_token  = (string) get_option('woolsn_telegram_bot_token', '');
        $chat_id    = (string) get_option('woolsn_telegram_chat_id', '');

        return $enabled && $bot_token !== '' && $chat_id !== '';
    }

    /**
     * @param array<string, mixed> $data
     */
    public function send_notification(array $data): bool
    {
        $this->last_error = null;

        if (! $this->is_enabled()) {
            $this->last_error = __('Telegram alerts are disabled.', 'stock-guardian-pro');
            return false;
        }

        $bot_token = trim((string) get_option('woolsn_telegram_bot_token', ''));
        $chat_id   = trim((string) get_option('woolsn_telegram_chat_id', ''));

        $message = $this->build_message($data);

        $response = wp_remote_post(
            sprintf('https://api.telegram.org/bot%s/sendMessage', rawurlencode($bot_token)),
            [
                'timeout' => 12,
                'body'    => [
                    'chat_id'                  => $chat_id,
                    'text'                     => $message,
                    'disable_web_page_preview' => true,
                ],
            ]
        );

        if (is_wp_error($response)) {
            $this->log_warning(sprintf('Telegram request error: %s', $response->get_error_message()));
            $this->last_error = $response->get_error_message();
            return false;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code < 200 || $code >= 300) {
            $body = wp_remote_retrieve_body($response);
            $this->log_warning(
                sprintf(
                    'Telegram API responded with %1$d: %2$s',
                    $code,
                    $body !== '' ? $body : 'empty response'
                )
            );
            $this->last_error = $body !== '' ? $body : sprintf(
                /* translators: %d Telegram API response code */
                __('Unexpected status code %d.', 'stock-guardian-pro'),
                $code
            );
            return false;
        }

        $this->last_error = null;

        return true;
    }

    /**
     * @param array<string, mixed> $data
     */
    private function build_message(array $data): string
    {
        $lines   = [];
        $lines[] = '📉 Stock Guardian Alert';
        $lines[] = sprintf('Product: %s', $data['product_name'] ?? '');

        if (! empty($data['product_sku'])) {
            $lines[] = sprintf('SKU: %s', $data['product_sku']);
        }

        if (isset($data['stock'])) {
            $lines[] = sprintf('Stock: %d', (int) $data['stock']);
        }

        if (isset($data['threshold'])) {
            $lines[] = sprintf('Threshold: %d', (int) $data['threshold']);
        }

        if (! empty($data['product_admin_url']) && wp_http_validate_url((string) $data['product_admin_url'])) {
            $lines[] = sprintf('Edit: %s', $data['product_admin_url']);
        }

        if (! empty($data['product_public_url']) && wp_http_validate_url((string) $data['product_public_url'])) {
            $lines[] = sprintf('View: %s', $data['product_public_url']);
        }

        return implode("\n", array_filter($lines));
    }

    private function log_warning(string $message): void
    {
        /** @var LoggerService|null $logger */
        $logger = $this->plugin->service(LoggerService::class);

        if ($logger instanceof LoggerService) {
            $logger->warning($message);
        }
    }

    public function get_last_error(): ?string
    {
        return $this->last_error;
    }
}

