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> 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 { Items = pagedEntities.Items.Select(EntityMapper.MapEntity), TotalItems = pagedEntities.TotalItems, Page = pagedEntities.Page, PageSize = pagedEntities.PageSize }; } public async Task 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(product); } public async Task> 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 { Items = pagedEntities.Items.Select(EntityMapper.MapEntity), TotalItems = pagedEntities.TotalItems, Page = pagedEntities.Page, PageSize = pagedEntities.PageSize }; } public async Task CreateAsync(EProduct entity) { if (entity == null) throw new ArgumentNullException(nameof(entity), "El producto no puede ser nulo."); try { var product = EntityMapper.MapEntity(entity); await _context.PhSProducts.AddAsync(product); await _context.SaveChangesAsync(); return EntityMapper.MapEntity(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 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 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 } }