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 PeopleService
    {
        private readonly HttpClient _http;
        private readonly IJSRuntime _js;

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

        // Buscar personas
        public async Task<PagedResult<EPerson>?> SearchPeopleAsync(PeopleSearchParams searchParams)
        {
            var url = $"api/People/search?" +
                      $"name={searchParams.Name}&" +
                      $"email={searchParams.Email}&" +
                      $"page={searchParams.Page}&" +
                      $"pageSize={searchParams.PageSize}";
            return await _http.GetFromJsonAsync<PagedResult<EPerson>>(url);
        }

        public async Task ExportFilteredAsync(PeopleSearchParams searchParams)
        {
            try
            {
                var content = new StringContent(JsonSerializer.Serialize(searchParams), Encoding.UTF8, "application/json");
                var response = await _http.PostAsync("api/People/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}_vendedores.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);
            }
        }

        // Obtener una persona por Id (para formulario)
        public async Task<EPerson?> GetPersonByIdAsync(int id)
        {
            return await _http.GetFromJsonAsync<EPerson>($"api/People/{id}");
        }

        // Crear nueva persona
        public async Task CreatePersonAsync(EPerson person)
        {
            var content = new StringContent(JsonSerializer.Serialize(person), Encoding.UTF8, "application/json");
            var response = await _http.PostAsync("api/People/create", content); // CAMBIADO

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


        // Actualizar persona existente
        public async Task UpdatePersonAsync(EPerson person)
        {
            var content = new StringContent(JsonSerializer.Serialize(person), Encoding.UTF8, "application/json");
            var response = await _http.PutAsync("api/People/update", content); // CAMBIADO

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

    }
}
