using Domain.Entities;
using Domain.Generics;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Models.Helpers;
using Models.Interfaces;
using Models.Models;

namespace Models.Repositories
{
    public class PhSPatientRepository(PhronCareOperationsHubContext context, ILogger<PhSPatientRepository> logger) : IPhSPatientRepository
    {
        #region Declaraciones y Constructor
        private readonly PhronCareOperationsHubContext _context = context;
        #endregion
        #region Métodos de clase
        public async Task<PagedResult<EPatient>> GetAllAsync(int page = 1, int pageSize = 50)
        {
            var query = _context.PhSPatients
                .Include(p => p.Customer)
                .Include(p => p.Documenttypes)
                .AsQueryable();

            var pagedEntities = await query.ToPagedResultAsync(page, pageSize);

            return new PagedResult<EPatient>
            {
                Items = pagedEntities.Items.Select(EntityMapper.MapEntity<PhSPatient, EPatient>),
                TotalItems = pagedEntities.TotalItems,
                Page = pagedEntities.Page,
                PageSize = pagedEntities.PageSize
            };
        }
        public async Task<EPatient?> GetByIdAsync(int id)
        {
            var patient = await _context.PhSPatients
                .Include(p => p.Customer)
                .Include(p => p.Documenttypes)
                .FirstOrDefaultAsync(p => p.Id == id);

            return patient != null ? EntityMapper.MapEntity<PhSPatient, EPatient>(patient) : null;
        }
        public async Task<PagedResult<EPatient>> SearchAsync(
            string? name,
            string? document,
            int page = 1,
            int pageSize = 50)
        {
            var query = _context.PhSPatients
                .Include(p => p.Documenttypes)
                .Include(p => p.Customer)
                .AsQueryable();

            if (!string.IsNullOrWhiteSpace(name))
            {
                var lowered = name.ToLower();
                query = query.Where(p =>
                    p.Firstname.ToLower().Contains(lowered) ||
                    p.Lastname.ToLower().Contains(lowered));
            }

            if (!string.IsNullOrWhiteSpace(document))
            {
                query = query.Where(p =>
                    EF.Functions.Like(p.DocumentNumber!, $"%{document}%") || EF.Functions.Like(p.AffiliateNumber!, $"%{document}%"));
            }

            var pagedEntities = await query.ToPagedResultAsync(page, pageSize);

            return new PagedResult<EPatient>
            {
                Items = pagedEntities.Items.Select(EntityMapper.MapEntity<PhSPatient, EPatient>),
                TotalItems = pagedEntities.TotalItems,
                Page = pagedEntities.Page,
                PageSize = pagedEntities.PageSize
            };
        }
        public async Task<EPatient> CreateAsync(EPatient entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity), "El paciente no puede ser nulo.");

            try
            {
                var patient = EntityMapper.MapEntity<EPatient, PhSPatient>(entity);
                await _context.PhSPatients.AddAsync(patient);
                await _context.SaveChangesAsync();
                return EntityMapper.MapEntity<PhSPatient, EPatient>(patient);
            }
            catch (DbUpdateException dbEx)
            {
                throw new Exception("Error al guardar el paciente en la base de datos.", dbEx);
            }
            catch (Exception ex)
            {
                throw new Exception("Error inesperado al crear el paciente: " + ex.Message, ex);
            }
        }
        public async Task<bool> UpdateAsync(EPatient entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            try
            {
                var existingPatient = await _context.PhSPatients
                    .FirstOrDefaultAsync(p => p.Id == entity.Id);

                if (existingPatient == null)
                    return false;

                EntityMapper.MapEntityToExisting(entity, existingPatient);

                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public async Task<bool> DeleteAsync(int id)
        {
            var patient = await _context.PhSPatients.FindAsync(id);
            if (patient == null) return false;

            _context.PhSPatients.Remove(patient);
            await _context.SaveChangesAsync();
            return true;
        }
        #endregion
    }
}
