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

namespace Models.Repositories
{
    public class PhSProductRepository(PhronCareOperationsHubContext context) : IPhSProductRepository
    {
        #region Declaraciones y Constructor
        private readonly PhronCareOperationsHubContext _context = context;
        #endregion

        #region Métodos de clase
        public async Task<PagedResult<EProduct>> GetAllAsync(int page = 1, int pageSize = 50)
        {
            var query = _context.PhSProducts
                .Include(p => p.Businessunits)
                .Include(p => p.Category)
                .AsQueryable();

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

            return new PagedResult<EProduct>
            {
                Items = pagedEntities.Items.Select(EntityMapper.MapEntity<PhSProduct, EProduct>),
                TotalItems = pagedEntities.TotalItems,
                Page = pagedEntities.Page,
                PageSize = pagedEntities.PageSize
            };
        }
        public async Task<EProduct?> GetByIdAsync(int id)
        {
            var product = await _context.PhSProducts
                .Include(p => p.Businessunits)
                .Include(p => p.Category)
                .FirstOrDefaultAsync(p => p.Id == id);
            return product is null ? null : EntityMapper.MapEntity<PhSProduct, EProduct>(product);
        }
        public async Task<PagedResult<EProduct>> SearchAsync(string? term, int page = 1, int pageSize = 50)
        {
            var query = _context.PhSProducts
                .Include(p => p.Businessunits)
                .Include(p => p.Category)
                .AsQueryable();

            if (!string.IsNullOrWhiteSpace(term))
            {
                term = term.ToLower();
                query = query.Where(p =>
                    p.Name.ToLower().Contains(term) ||
                    p.Description.ToLower().Contains(term));
            }

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

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

                await _context.PhSProducts.AddAsync(product);
                await _context.SaveChangesAsync();

                return EntityMapper.MapEntity<PhSProduct, EProduct>(product);
            }
            catch (DbUpdateException dbEx)
            {
                throw new Exception("Error al guardar el producto en la base de datos. Verificá integridad de datos.", dbEx);
            }
            catch (Exception ex)
            {
                throw new Exception("Error inesperado al crear el producto: " + ex.Message, ex);
            }
        }
        public async Task<bool> UpdateAsync(EProduct entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));
            try
            {
                var existingProduct = await _context.PhSProducts
                    .Include(p => p.Businessunits)
                    .Include(p => p.Category)
                    .FirstOrDefaultAsync(p => p.Id == entity.Id);

                if (existingProduct == null)
                    return false;

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

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

            _context.PhSProducts.Remove(product);
            await _context.SaveChangesAsync();
            return true;
        }
        #endregion
    }

}
