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

namespace Models.Repositories.Stock
{
    public class PhLSMProductDivisionRepository(PhronCareOperationsHubContext context) : IPhLSMProductDivisionRepository
    {
        private readonly PhronCareOperationsHubContext _context = context;

        public async Task<PagedResult<ELSProductDivision>> GetAllAsync(int page = 1, int pageSize = 50)
        {
            var query = _context.PhLsmProductDivisions.AsQueryable();

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

            return new PagedResult<ELSProductDivision>
            {
                Items = pagedEntities.Items.Select(EntityMapper.MapEntity<PhLsmProductDivision, ELSProductDivision>),
                TotalItems = pagedEntities.TotalItems,
                Page = pagedEntities.Page,
                PageSize = pagedEntities.PageSize
            };
        }

        public async Task<ELSProductDivision?> GetByIdAsync(int id)
        {
            var entity = await _context.PhLsmProductDivisions.FirstOrDefaultAsync(x => x.Id == id);
            return entity is null ? null : EntityMapper.MapEntity<PhLsmProductDivision, ELSProductDivision>(entity);
        }

        public async Task<PagedResult<ELSProductDivision>> SearchAsync(string? term, int page = 1, int pageSize = 50)
        {
            var query = _context.PhLsmProductDivisions.AsQueryable();

            if (!string.IsNullOrWhiteSpace(term))
            {
                term = term.ToLower();
                query = query.Where(x =>
                    (x.Code != null && x.Code.ToLower().Contains(term)) ||
                    (x.Name != null && x.Name.ToLower().Contains(term)) ||
                    (x.Description != null && x.Description.ToLower().Contains(term))
                );
            }
            var pagedEntities = await query.ToPagedResultAsync(page, pageSize);

            return new PagedResult<ELSProductDivision>
            {
                Items = pagedEntities.Items.Select(EntityMapper.MapEntity<PhLsmProductDivision, ELSProductDivision>),
                TotalItems = pagedEntities.TotalItems,
                Page = pagedEntities.Page,
                PageSize = pagedEntities.PageSize
            };
        }

        public async Task<ELSProductDivision> CreateAsync(ELSProductDivision entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            try
            {
                var mapped = EntityMapper.MapEntity<ELSProductDivision, PhLsmProductDivision>(entity);
                _context.PhLsmProductDivisions.Add(mapped);
                await _context.SaveChangesAsync();
                return EntityMapper.MapEntity<PhLsmProductDivision, ELSProductDivision>(mapped);
            }
            catch (DbUpdateException dbEx)
            {
                throw new Exception("Error al guardar la división de producto. Verificá integridad de datos.", dbEx);
            }
            catch (Exception ex)
            {
                throw new Exception("Error inesperado al crear la división: " + ex.Message, ex);
            }
        }

        public async Task<bool> UpdateAsync(ELSProductDivision entity)
        {
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            try
            {
                var existing = await _context.PhLsmProductDivisions.FirstOrDefaultAsync(x => x.Id == entity.Id);
                if (existing == null) return false;

                EntityMapper.MapEntityToExisting(entity, existing);
                await _context.SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var existing = await _context.PhLsmProductDivisions.FindAsync(id);
            if (existing == null) return false;

            _context.PhLsmProductDivisions.Remove(existing);
            await _context.SaveChangesAsync();
            return true;
        }
        public async Task<List<string>> GetAllCodesAsync()
        {
            return await _context.PhLsmProductDivisions
                                 .Where(x => !string.IsNullOrEmpty(x.Code))
                                 .Select(x => x.Code!)
                                 .ToListAsync();
        }

        public async Task<bool> ExistsByCodeAsync(string code)
        {
            return await _context.PhLsmProductDivisions
                                 .AnyAsync(x => x.Code != null && x.Code == code);
        }

    }
}
