using DigitalData.Core.Infrastructure;
using DigitalData.UserManager.Domain.Entities;
using DigitalData.UserManager.Infrastructure.Contracts;
using Microsoft.EntityFrameworkCore;

namespace DigitalData.UserManager.Infrastructure.Repositories
{
    public class GroupRepository<TDbContext> : CRUDRepository<Group, int, TDbContext>, IGroupRepository
        where TDbContext : DbContext, IUserManagerDbContext
    {
        private readonly IGroupOfUserRepository _gouRepo;

        private readonly IUserRepRepository _uRepRepo;

        public GroupRepository(TDbContext dbContext, IGroupOfUserRepository gouRepo, IUserRepRepository userRepRepository) : base(dbContext, dbContext.Groups)
        {
            _gouRepo = gouRepo;
            _uRepRepo = userRepRepository;
        }

        //TODO: instead of this implmenet .OnDelete(DeleteBehavior.ClientCascade) in DbContext
        public override async Task<bool> DeleteAsync(Group group)
        {
            var gou_list = await _gouRepo.ReadAsync(readOnly: false, groupId: group.Id);
            if (gou_list.Any())
                _dbContext.RemoveRange(gou_list);
            
            var uRep_list = await _uRepRepo.ReadAllAsync(readOnly: false, groupId: group.Id);
            if (uRep_list.Any())
                _dbContext.RemoveRange(uRep_list);

            uRep_list = await _uRepRepo.ReadAllAsync(readOnly: false, repGroupId: group.Id);
            if (uRep_list.Any())
                _dbContext.RemoveRange(uRep_list);

            return await base.DeleteAsync(group);
        }
    }
}