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

namespace Core.Services
{
    public class InstitutionService : IInstitutionDom
    {
        #region Declaraciones y Constructor
        private readonly IPhSInstitutionRepository _repository;
        public InstitutionService(IPhSInstitutionRepository repository)
        {
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        }
        #endregion
        #region Métodos
        public async Task<PagedResult<EInstitution>> 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<EInstitution?> 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<EInstitution> CreateAsync(EInstitution entity)
        {
            if (entity is null)
                throw new ArgumentNullException(nameof(entity), "La institución no puede ser nula.");

            if (string.IsNullOrWhiteSpace(entity.Name) )
                throw new ArgumentException("Debe completar el nombre de la institución.");

            if (string.IsNullOrWhiteSpace(entity.Type))
                throw new ArgumentException("Debe seleccionar un tipo de institución.");

            return await _repository.CreateAsync(entity);
        }
        public async Task<bool> UpdateAsync(EInstitution entity)
        {
            if (entity is null || entity.Id <= 0)
                throw new ArgumentException("La institución es inválida o no tiene un ID válido.");

            if (string.IsNullOrWhiteSpace(entity.Name))
                throw new ArgumentException("Debe completar el nombre de la institución.");

            if (string.IsNullOrWhiteSpace(entity.Type))
                throw new ArgumentException("Debe seleccionar un tipo de institución.");
            return await _repository.UpdateAsync(entity);
        }
        public async Task<PagedResult<EInstitution>> SearchAsync(string? name, string? type, string? province, int page = 1, int pageSize = 50)
        {
            try
            {
                return await _repository.SearchAsync(name, type, province, page, pageSize);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                throw new Exception($"{methodName} Message: {ex.Message}", ex);
            }
        }
        public Task<bool> DeleteAsync(int id)
        {
            throw new NotImplementedException();
        }
        public async Task<byte[]> ExportFilteredInstitutionsToExcelAsync(InstitutionSearchParams searchParams)
        {
            try
            {
                var searchResult = await SearchAsync(
                    searchParams.Name,
                    searchParams.Type,
                    searchParams.Province,
                    searchParams.Page,
                    searchParams.PageSize
                );

                if (searchResult?.Items is null || !searchResult.Items.Any())
                    throw new Exception("No se encontraron instituciones para exportar.");

                var stream = new XLSXExportBase();

                var data = searchResult.Items.Select(i => new
                {
                    i.Id,
                    i.Name,
                    i.Type,
                    i.City,
                    i.Province,
                    i.Email,
                    i.Phone,
                    i.Isactive
                }).ToList();

                return stream.ExportExcel(data);
            }
            catch (Exception ex)
            {
                var methodName = MethodBase.GetCurrentMethod()?.Name ?? "UnknownMethod";
                throw new Exception($"{methodName} Message: {ex.Message}", ex);
            }
        }
        #endregion
    }
}
