using Domain.Entities;
using Domain.Generics;
using Microsoft.EntityFrameworkCore;
using Models.Helpers;
using Models.Interfaces;
using Models.Models;
using System.Reflection.Metadata;

namespace Models.Repositories
{
    public class PhSProfessionalRepository(PhronCareOperationsHubContext context) : IPhSProfessionalRepository
    {
        #region Declaraciones y Constructor
        private readonly PhronCareOperationsHubContext _context = context;
        #endregion
        #region Métodos de clase
        public async Task<PagedResult<EProfessional>> GetAllAsync(int page = 1, int pageSize = 50)
        {
            var query = _context.PhSProfessionals
                .Include(p => p.Specialty)
                .AsQueryable();

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

            return new PagedResult<EProfessional>
            {
                Items = pagedEntities.Items.Select(EntityMapper.MapEntity<PhSProfessional, EProfessional>),
                TotalItems = pagedEntities.TotalItems,
                Page = pagedEntities.Page,
                PageSize = pagedEntities.PageSize
            };
        }
        public async Task<EProfessional?> GetByIdAsync(int id)
        {
            var professional = await _context.PhSProfessionals
                .Include(p => p.Specialty)
                .FirstOrDefaultAsync(p => p.Id == id);

            return professional != null ? EntityMapper.MapEntity<PhSProfessional, EProfessional>(professional) : null;
        }
        public async Task<PagedResult<EProfessional>> SearchAsync(string? fullname, string? document, string? type,
            int page = 1, int pageSize = 50)
        {
            var query = _context.PhSProfessionals
                .Include(p => p.Specialty)
                .AsQueryable();
            if (!string.IsNullOrWhiteSpace(fullname)) query = query.Where(c => c.Fullname.ToLower().Contains(fullname.ToLower()));
            if (!string.IsNullOrWhiteSpace(document) && document != "?")
            {
                query = query.Where(p =>
                                    EF.Functions.Like(p.DocumentNumber ?? "", $"%{document}%") ||
                                    EF.Functions.Like(p.License ?? "", $"%{document}%"));
            }
            if (!string.IsNullOrWhiteSpace(type)) query = query.Where(c => c.Type.ToLower().Contains(type.ToLower()));

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

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

            try
            {
                var dbEntity = EntityMapper.MapEntity<EProfessional, PhSProfessional>(entity);
                await _context.PhSProfessionals.AddAsync(dbEntity);
                await _context.SaveChangesAsync();

                return EntityMapper.MapEntity<PhSProfessional, EProfessional>(dbEntity);
            }
            catch (DbUpdateException dbEx)
            {
                throw new Exception("Error al guardar el profesional en la base de datos.", dbEx);
            }
            catch (Exception ex)
            {
                throw new Exception("Error inesperado al crear el profesional: " + ex.Message, ex);
            }
        }
        public async Task<bool> UpdateAsync(EProfessional entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            try
            {
                var existing = await _context.PhSProfessionals
                    .FirstOrDefaultAsync(p => p.Id == entity.Id);

                if (existing == null)
                    return false;

                EntityMapper.MapEntityToExisting(entity, existing);
                await _context.SaveChangesAsync();

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

            _context.PhSProfessionals.Remove(entity);
            await _context.SaveChangesAsync();

            return true;
        }
        #endregion
    }
}