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

namespace Core.Services
{
    public class CustomerService: ICustomerDom
    {
        #region Declaraciones y Constructor
        private readonly IPhSCustomerRepository _repository;
        public CustomerService(IPhSCustomerRepository customerRepository)
        {
            _repository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
        }
        #endregion
        #region Metodos
        public async Task<PagedResult<ECustomer>> GetAllAsync(int page = 1, int pageSize = 50)
        {
            try
            {
                return await _repository.GetAllAsync(page, pageSize);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                throw new Exception($"{methodName} Message: {ex.Message}", ex);
            }
        }
        public async Task<ECustomer?> GetByIdAsync(int id)
        {
            try
            {
                return await _repository.GetByIdAsync(id);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                throw new Exception($"{methodName} Message: {ex.Message}", ex);
            }
        }
        public async Task<ECustomer> CreateAsync(ECustomer entity)
        {
            if (entity is null)
                throw new ArgumentNullException(nameof(entity), "El cliente no puede ser nulo.");

            if (!entity.AccounttypesId.HasValue)
                throw new ArgumentException("Debe seleccionar un tipo de cuenta.", nameof(entity.AccounttypesId));

            if (entity.PhSCustomerDocuments == null || !entity.PhSCustomerDocuments.Any())
                throw new ArgumentException("El cliente debe tener al menos un documento (por ejemplo, CUIT).", nameof(entity.PhSCustomerDocuments));

            return await _repository.CreateAsync(entity);
        }
        public async Task<PagedResult<ECustomer>> SearchAsync(
            string? name, string? email, string? document,
            int page = 1, int pageSize = 50)
        {
            try
            {
                return await _repository.SearchAsync(name, email, document, page, pageSize);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                throw new Exception($"{methodName} Message: {ex.Message}", ex);
            }
        }
        public async Task<bool> UpdateAsync(ECustomer entity)
        {
            if (entity is null)
                throw new ArgumentNullException(nameof(entity), "El cliente no puede ser nulo.");

            if (!entity.AccounttypesId.HasValue)
                throw new ArgumentException("Debe seleccionar un tipo de cuenta.", nameof(entity.AccounttypesId));

            if (entity.PhSCustomerDocuments == null || !entity.PhSCustomerDocuments.Any())
                throw new ArgumentException("El cliente debe tener al menos un documento (por ejemplo, CUIT).", nameof(entity.PhSCustomerDocuments));

            return await _repository.UpdateAsync(entity);
        }
        public Task<bool> DeleteAsync(int id)
        {
            throw new NotImplementedException();
        }
        public async Task<byte[]> ExportFilteredCustomersToExcelAsync(CustomerSearchParams searchParams)
        {
            try
            {
                // Realiza la búsqueda de clientes con los parámetros proporcionados
                var searchResult = await SearchAsync(
                    searchParams.Name,
                    searchParams.Email,
                    searchParams.Document,
                    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.BusinessName,
                    c.Active,
                    c.HasCreditAccount,
                    c.CreditLimit,
                    Address = c.PhSCustomerAddresses.FirstOrDefault()?.Streetaddress1,
                    Email = c.PhSCustomerAddresses.FirstOrDefault()?.Email,
                    Document = c.PhSCustomerDocuments.FirstOrDefault()?.DocumentNumber
                }).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
    }
}