using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;


namespace PARR.DAL.Repositories.Unit
{
    internal class UnitRepository : BaseRepository<Domain.Entities.Unit.Unit>, IUnitRepository
    {
        public UnitRepository(DataContext dataContext, ILogger<UnitRepository> logger) : base(logger, dataContext) { }


        public IQueryable<Domain.Entities.Unit.Unit> GetWithIncludes()
        {
            return Get()
                    .Include(t => t.UnitValues)
                        .ThenInclude(t => t.Field)
                    .Include(t => t.UnitValues)
                        .ThenInclude(t => t.Value);
        }


        public IQueryable<PARR.Domain.Entities.Unit.Unit> GetUnitByFieldAndValue(IQueryable<PARR.Domain.Entities.Unit.Unit> query, Guid fieldId, string valueMask, bool isInverse = false)
        {
            //TODO: вынесено из UnitFilterService

            if (isInverse)
            {
                query = query.Where(u => !u.UnitValues.Any(v =>
                    v.FieldId == fieldId &&
                    EF.Functions.ILike(v.Value.Value, valueMask)));
            }
            else
            {
                query = query.Where(u => u.UnitValues.Any(v =>
                    v.FieldId == fieldId &&
                    EF.Functions.ILike(v.Value.Value, valueMask)));
            }

            return query;
        }

        public IQueryable<Guid> GetInitialUnitIds(string dbValueMask)
        {
            //TODO: вынесено из UnitFilterService

            //var initialUnitIds = await unitService.Get().AsNoTracking()
            //.Where(unit => EF.Functions.ILike(unit.Name, dbValueMask))
            //.Select(u => u.Id)
            //.ToListAsync(cancellationToken);

            return Get().AsNoTracking()
                            .Where(unit => EF.Functions.ILike(unit.Name, dbValueMask))
                            .Select(u => u.Id);
        }


    }
}
