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

namespace DigitalData.UserManager.Infrastructure.Repositories
{
    public class UserRepository<TDbContext> : CRUDRepository<User, int, TDbContext>, IUserRepository
        where TDbContext : DbContext, IUserManagerDbContext
    {
        private IModuleOfUserRepository _moduleOfUserRepo;
        private IGroupOfUserRepository _groupOfUserRepo;
        public UserRepository(TDbContext dbContext, IModuleOfUserRepository moduleOfUserRepo, IGroupOfUserRepository groupOfUserRepo) : base(dbContext, dbContext.Users)
        {
            _moduleOfUserRepo = moduleOfUserRepo;
            _groupOfUserRepo = groupOfUserRepo;
        }

        public async Task<IEnumerable<User>> ReadByModuleIdAsync(int moduleId)
        {
            var mous = _moduleOfUserRepo.ReadByModuleId(moduleId).Select<ModuleOfUser, int>(mos => mos.UserId);
            return await _dbSet.Where<User>(u => mous.Contains(u.Id)).ToListAsync();
        }

        public async Task<IEnumerable<User>> ReadByGroupIdAsync(int groupId)
        {
            var gous = _groupOfUserRepo.ReadByGroupId(groupId).Select(gou => gou.UserId);
            return await _dbSet.Where<User>(u => gous.Contains(u.Id)).ToListAsync();
        }

        public async Task<IEnumerable<User>> ReadUnassignedByModuleIdAsync(int moduleId)
        {
            var mous = _moduleOfUserRepo.ReadByModuleId(moduleId).Select<ModuleOfUser, int>(mos => mos.UserId);
            return await _dbSet.Where<User>(u => !mous.Contains(u.Id)).ToListAsync();
        }

        public async Task<IEnumerable<User>> ReadUnassignedByGroupIdAsync(int groupId)
        {
            var gous = _groupOfUserRepo.ReadByGroupId(groupId).Select<GroupOfUser, int>(gou => gou.UserId);
            return await _dbSet.Where<User>(u => !gous.Contains(u.Id)).ToListAsync();
        }

        public async Task<User?> ReadByUsernameAsync(string username)
        {
            return await _dbSet.Where(user => user.Username == username).FirstOrDefaultAsync();
        }
    }
}