using System.Net.Http.Json;
using Microsoft.Extensions.Logging;
using LittleShop.Client.Models;

namespace LittleShop.Client.Services;

public class MessageService : IMessageService
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<MessageService> _logger;

    public MessageService(HttpClient httpClient, ILogger<MessageService> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<List<CustomerMessage>> GetPendingMessagesAsync(string platform = "Telegram")
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/bot/messages/pending?platform={platform}");
            
            if (response.IsSuccessStatusCode)
            {
                var messages = await response.Content.ReadFromJsonAsync<List<CustomerMessage>>();
                return messages ?? new List<CustomerMessage>();
            }
            
            _logger.LogWarning("Failed to get pending messages: {StatusCode}", response.StatusCode);
            return new List<CustomerMessage>();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting pending messages");
            return new List<CustomerMessage>();
        }
    }

    public async Task<bool> MarkMessageAsSentAsync(Guid messageId, string? platformMessageId = null)
    {
        try
        {
            var url = $"api/bot/messages/{messageId}/mark-sent";
            if (!string.IsNullOrEmpty(platformMessageId))
            {
                url += $"?platformMessageId={platformMessageId}";
            }

            var response = await _httpClient.PostAsync(url, null);
            return response.IsSuccessStatusCode;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error marking message {MessageId} as sent", messageId);
            return false;
        }
    }

    public async Task<bool> MarkMessageAsFailedAsync(Guid messageId, string reason)
    {
        try
        {
            var response = await _httpClient.PostAsJsonAsync($"api/bot/messages/{messageId}/mark-failed", reason);
            return response.IsSuccessStatusCode;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error marking message {MessageId} as failed", messageId);
            return false;
        }
    }

    public async Task<bool> CreateCustomerMessageAsync(object messageData)
    {
        try
        {
            var response = await _httpClient.PostAsJsonAsync("api/bot/messages/customer-create", messageData);
            return response.IsSuccessStatusCode;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error creating customer message");
            return false;
        }
    }

    public async Task<List<CustomerMessage>?> GetCustomerMessagesAsync(Guid customerId)
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/bot/messages/customer/{customerId}");
            
            if (response.IsSuccessStatusCode)
            {
                var messages = await response.Content.ReadFromJsonAsync<List<CustomerMessage>>();
                return messages ?? new List<CustomerMessage>();
            }
            
            _logger.LogWarning("Failed to get customer messages: {StatusCode}", response.StatusCode);
            return new List<CustomerMessage>();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting customer messages");
            return new List<CustomerMessage>();
        }
    }
}