using Core.Interfaces;
using Domain.Entities;
using Domain.Generics;
using Models.Interfaces;
using System.Reflection;
using Transversal.Services;

namespace Core.Services
{
    public class PeopleService : IPeopleDom
    {
        #region Declaraciones
        private readonly IPhSPeopleRepository _peopleRepository ;
        #endregion
        public PeopleService(IPhSPeopleRepository peopleRepository)
        {
            _peopleRepository = peopleRepository ?? throw new ArgumentNullException(nameof(peopleRepository));
        }
        #region Métodos
        public async Task<PagedResult<EPerson>> GetAllAsync(int page = 1, int pageSize = 50)
        {
            return await _peopleRepository.GetAllAsync(page, pageSize);
        }
        public async Task<PagedResult<EPerson>> SearchAsync(string? name, string? email,
            int page = 1, int pageSize = 50)
        {
            return await _peopleRepository.SearchAsync(name,email,page,pageSize);
        }
        public async Task<EPerson?> GetByIdAsync(int id)
        {
            return await _peopleRepository.GetByIdAsync(id);
        }

        public async Task<EPerson> AddAsync(EPerson person)
        {
            return await _peopleRepository.AddAsync(person);
        }

        public async Task<bool> UpdateAsync(EPerson person)
        {
            var existing = await _peopleRepository.GetByIdAsync(person.Id);
            if (existing == null)
                return false;

            await _peopleRepository.UpdateAsync(person);
            return true;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var existing = await _peopleRepository.GetByIdAsync(id);
            if (existing == null)
                return false;

            await _peopleRepository.DeleteAsync(id);
            return true;
        }
        public async Task<byte[]> ExportFilteredCustomersToExcelAsync(PeopleSearchParams searchParams)
        {
            try
            {
                // Realiza la búsqueda de clientes con los parámetros proporcionados
                var searchResult = await SearchAsync(
                    searchParams.Name,
                    searchParams.Email,
                    searchParams.Page,
                    searchParams.PageSize
                );
                // Verifica que se hayan encontrado resultados
                if (searchResult?.Items is null || !searchResult.Items.Any())
                {
                    throw new Exception("No se encontraron clientes para exportar.");
                }
                // Llamamos a un método que exporta los datos a Excel
                var stream = new XLSXExportBase();
                // Convertimos los resultados de la búsqueda a un formato adecuado para el exportador
                var customersData = searchResult.Items.Select(c => new
                {
                    c.Id,
                    c.Name,
                    c.Email,
                    c.Phone,
                    c.DefaultCommissionPercent,
                    c.Active
                }).ToList();
                // Genera el archivo Excel
                var excelFile = stream.ExportExcel(customersData);
                // Devuelve el archivo Excel como un array de bytes
                return excelFile;
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                throw new Exception($"{ex.Message}", ex);
            }
        }
        #endregion
    }
}
