using Domain.Entities;
using Domain.Generics;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Microsoft.JSInterop;
using System.Reflection;

namespace phronCare.UIBlazor.Services.Sales
{
    public class ProductService
    {
        private readonly HttpClient _http;
        private readonly IJSRuntime _js;

        public ProductService(HttpClient http, IJSRuntime js)
        {
            _http = http;
            _js = js;
        }

        public async Task<List<EProduct>> GetAllAsync()
        {
            var result = await _http.GetFromJsonAsync<List<EProduct>>("/api/Product/GetAll");
            return result ?? new List<EProduct>();
        }

        public async Task<EProduct> GetByIdAsync(int id)
        {
            var result = await _http.GetFromJsonAsync<EProduct>($"/api/Product/{id}");
            return result ?? new EProduct();
        }

        public async Task<HttpResponseMessage> CreateAsync(EProduct product)
        {
            return await _http.PostAsJsonAsync("/api/Product/Create", product);
        }

        public async Task<HttpResponseMessage> UpdateAsync(EProduct product)
        {
            return await _http.PutAsJsonAsync("/api/Product/Update", product);
        }

        public async Task<PagedResult<EProduct>?> SearchProductsAsync(ProductSearchParams searchParams)
        {
            var url = $"api/Product/search?" +
                      $"term={searchParams.Term}&" +
                      $"page={searchParams.Page}&" +
                      $"pageSize={searchParams.PageSize}";
            return await _http.GetFromJsonAsync<PagedResult<EProduct>>(url);
        }

        public async Task ExportFilteredAsync(ProductSearchParams searchParams)
        {
            try
            {
                var content = new StringContent(JsonSerializer.Serialize(searchParams), Encoding.UTF8, "application/json");
                var response = await _http.PostAsync("api/Product/exportfiltered", content);

                if (!response.IsSuccessStatusCode)
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    throw new Exception(errorContent);
                }

                var bytes = await response.Content.ReadAsByteArrayAsync();
                var base64 = Convert.ToBase64String(bytes);
                var timestamp = DateTime.Now.ToString("yyyyMMddHHmm");
                var fileName = $"{timestamp}_productos.xlsx";
                await _js.InvokeVoidAsync("saveAsFile", fileName, base64);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                var message = ex.Message ?? "No message provided";
                throw new Exception($"{message}", ex);
            }
        }
    }
}
