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 CustomerService
    {
        private readonly HttpClient _http;
        private readonly IJSRuntime _js;
        public CustomerService(HttpClient http, IJSRuntime js)
        {
            _http = http;
            _js = js;
        }
        public async Task<PagedResult<ECustomer>?> SearchCustomersAsync(CustomerSearchParams searchParams)
        {
            var url = $"api/Customer/search?" +
                      $"name={searchParams.Name}&" +
                      $"email={searchParams.Email}&" +
                      $"document={searchParams.Document}&" +
                      $"page={searchParams.Page}&" +
                      $"pageSize={searchParams.PageSize}";
            return await _http.GetFromJsonAsync<PagedResult<ECustomer>>(url);
        }
        public async Task ExportFilteredAsync(CustomerSearchParams searchParams)
        {
            try
            {
                var content = new StringContent(JsonSerializer.Serialize(searchParams), Encoding.UTF8, "application/json");
                var response = await _http.PostAsync("api/Customer/exportfiltered", content);

                //response.EnsureSuccessStatusCode();
                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}_clientes.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);
            }
        }
    }
}
