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

namespace LittleShop.Client.Services;

public class OrderService : IOrderService
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<OrderService> _logger;
    
    public OrderService(HttpClient httpClient, ILogger<OrderService> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }
    
    public async Task<ApiResponse<Order>> CreateOrderAsync(CreateOrderRequest request)
    {
        try
        {
            var response = await _httpClient.PostAsJsonAsync("api/orders", request);
            
            if (response.IsSuccessStatusCode)
            {
                var order = await response.Content.ReadFromJsonAsync<Order>();
                if (order != null)
                    return ApiResponse<Order>.Success(order, response.StatusCode);
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<Order>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create order");
            return ApiResponse<Order>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }
    
    public async Task<ApiResponse<List<Order>>> GetOrdersByIdentityAsync(string identityReference)
    {
        try
        {
            var response = await _httpClient.GetAsync(
                $"api/orders/by-identity/{Uri.EscapeDataString(identityReference)}");
            
            if (response.IsSuccessStatusCode)
            {
                var orders = await response.Content.ReadFromJsonAsync<List<Order>>();
                return ApiResponse<List<Order>>.Success(orders ?? new List<Order>());
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<List<Order>>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get orders for identity {Identity}", identityReference);
            return ApiResponse<List<Order>>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }

    public async Task<ApiResponse<List<Order>>> GetOrdersByCustomerIdAsync(Guid customerId)
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/orders/by-customer/{customerId}");
            
            if (response.IsSuccessStatusCode)
            {
                var orders = await response.Content.ReadFromJsonAsync<List<Order>>();
                return ApiResponse<List<Order>>.Success(orders ?? new List<Order>());
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<List<Order>>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get orders for customer {CustomerId}", customerId);
            return ApiResponse<List<Order>>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }
    
    public async Task<ApiResponse<Order>> GetOrderByIdAsync(Guid id)
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/orders/{id}");
            
            if (response.IsSuccessStatusCode)
            {
                var order = await response.Content.ReadFromJsonAsync<Order>();
                if (order != null)
                    return ApiResponse<Order>.Success(order);
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<Order>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order {OrderId}", id);
            return ApiResponse<Order>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }

    public async Task<ApiResponse<Order>> GetOrderByCustomerIdAsync(Guid customerId, Guid orderId)
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/orders/by-customer/{customerId}/{orderId}");
            
            if (response.IsSuccessStatusCode)
            {
                var order = await response.Content.ReadFromJsonAsync<Order>();
                if (order != null)
                    return ApiResponse<Order>.Success(order);
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<Order>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get order {OrderId} for customer {CustomerId}", orderId, customerId);
            return ApiResponse<Order>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }
    
    public async Task<ApiResponse<CryptoPayment>> CreatePaymentAsync(Guid orderId, int currency)
    {
        try
        {
            var request = new CreatePaymentRequest { Currency = currency };
            var response = await _httpClient.PostAsJsonAsync(
                $"api/orders/{orderId}/payments", request);
            
            if (response.IsSuccessStatusCode)
            {
                var payment = await response.Content.ReadFromJsonAsync<CryptoPayment>();
                if (payment != null)
                    return ApiResponse<CryptoPayment>.Success(payment, response.StatusCode);
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<CryptoPayment>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to create payment for order {OrderId}", orderId);
            return ApiResponse<CryptoPayment>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }
    
    public async Task<ApiResponse<List<CryptoPayment>>> GetOrderPaymentsAsync(Guid orderId)
    {
        try
        {
            var response = await _httpClient.GetAsync($"api/orders/{orderId}/payments");
            
            if (response.IsSuccessStatusCode)
            {
                var payments = await response.Content.ReadFromJsonAsync<List<CryptoPayment>>();
                return ApiResponse<List<CryptoPayment>>.Success(payments ?? new List<CryptoPayment>());
            }
            
            var error = await response.Content.ReadAsStringAsync();
            return ApiResponse<List<CryptoPayment>>.Failure(error, response.StatusCode);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get payments for order {OrderId}", orderId);
            return ApiResponse<List<CryptoPayment>>.Failure(
                ex.Message, 
                System.Net.HttpStatusCode.InternalServerError);
        }
    }
}