using Domain.Entities;
using Domain.Generics;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text;
using Microsoft.JSInterop;
using System.Reflection;
using System.Net.Http;
using phronCare.UIBlazor.Pages.Sales;

namespace phronCare.UIBlazor.Services.Sales
{
    public class ProfessionalService
    {
        private readonly HttpClient _http;
        private readonly IJSRuntime _js;
        public ProfessionalService(HttpClient http, IJSRuntime js)
        {
            _http = http;
            _js = js;
        }
        public async Task<PagedResult<EProfessional>?> SearchAsync(ProfessionalSearchParams searchParams)
        {
            var url = $"api/Professional/search?" +
                      $"fullname={searchParams.Fullname}&" +
                      $"document={searchParams.Document}&" +
                      $"type={searchParams.Type}&" +
                      $"page={searchParams.Page}&" +
                      $"pageSize={searchParams.PageSize}";
            return await _http.GetFromJsonAsync<PagedResult<EProfessional>>(url);
        }

        public async Task<EProfessional?> GetById(int id)
        {
            return await _http.GetFromJsonAsync<EProfessional>($"/api/Professional/{id}") ;
        }
        public async Task<HttpResponseMessage> CreateAsync(EProfessional professional)
        {
            return await _http.PostAsJsonAsync("/api/Professional/Create", professional);
        }
        public async Task<HttpResponseMessage> UpdateAsync(EProfessional professional)
        {
            return await _http.PutAsJsonAsync("/api/Professional/Update", professional);
        }
        public async Task ExportFilteredAsync(ProfessionalSearchParams searchParams)
        {
            try
            {
                var content = new StringContent(JsonSerializer.Serialize(searchParams), Encoding.UTF8, "application/json");
                var response = await _http.PostAsync("api/Professional/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}_profesionales.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);
            }
        }
    }
}
