using System.Net.Http.Json;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Users;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Managing.Application.Shared;

public class WebhookService : IWebhookService
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<WebhookService> _logger;

    public WebhookService(HttpClient httpClient, IConfiguration configuration, ILogger<WebhookService> logger)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    public async Task SendTradeNotification(User user, string message, bool isBadBehavior = false)
    {
        try
        {
            // Get the n8n webhook URL from configuration
            var webhookUrl = _configuration["N8n:WebhookUrl"];
            if (string.IsNullOrEmpty(webhookUrl))
            {
                _logger.LogWarning("N8n webhook URL not configured, skipping webhook notification");
                return;
            }

            // Prepare the payload for n8n webhook
            var payload = new
            {
                message = message,
                isBadBehavior = isBadBehavior,
                timestamp = DateTime.UtcNow,
                type = "trade_notification",
                telegramChannel = user.TelegramChannel
            };

            // Send the webhook notification
            var response = await _httpClient.PostAsJsonAsync(webhookUrl, payload);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation($"Successfully sent webhook notification for user {user.Name}");
            }
            else
            {
                _logger.LogWarning($"Failed to send webhook notification. Status: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error sending webhook notification");
        }
    }

    public async Task SendMessage(string message, string? telegramChannel = null)
    {
        try
        {
            // Get the n8n webhook URL from configuration
            var webhookUrl = _configuration["N8n:WebhookUrl"];
            if (string.IsNullOrEmpty(webhookUrl))
            {
                _logger.LogWarning("N8n webhook URL not configured, skipping webhook message");
                return;
            }

            // Prepare the payload for n8n webhook
            var payload = new
            {
                message = message,
                timestamp = DateTime.UtcNow,
                type = "general_message",
                telegramChannel = FormatTelegramChannel(telegramChannel)
            };

            // Send the webhook notification
            var response = await _httpClient.PostAsJsonAsync(webhookUrl, payload);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("Successfully sent webhook message");
            }
            else
            {
                _logger.LogWarning($"Failed to send webhook message. Status: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error sending webhook message");
        }
    }

    private string FormatTelegramChannel(string? telegramChannel)
    {
        if (string.IsNullOrEmpty(telegramChannel))
        {
            return string.Empty;
        }

        if (telegramChannel.StartsWith("100"))
        {
            return telegramChannel.Substring(3);
        }
        else if (telegramChannel.StartsWith("-100"))
        {
            return telegramChannel.Substring(4);
        }

        return telegramChannel;
    }
}