using Microsoft.EntityFrameworkCore; using Mws.Application.Common.Repositories; using Mws.Domain.Users; namespace Mws.Infrastructure.Persistence.Repositories; public class UserRepository(AppDbContext db) : RepositoryBase(db), IUserRepository { public Task GetByIdAsync(Guid id, CancellationToken ct = default) => Set.FirstOrDefaultAsync(u => u.Id == id, ct); public Task GetByIdWithRoleAsync(Guid id, CancellationToken ct = default) => Set.Include(u => u.Role).FirstOrDefaultAsync(u => u.Id == id, ct); public Task GetByUsernameWithRoleAsync(string username, CancellationToken ct = default) => Set.Include(u => u.Role).SingleOrDefaultAsync(u => u.Username == username, ct); public Task ExistsByUsernameAsync(string username, CancellationToken ct = default) => Set.AnyAsync(u => u.Username == username, ct); public Task ExistsByRoleIdAsync(Guid roleId, CancellationToken ct = default) => Set.AnyAsync(u => u.RoleId == roleId, ct); public Task GetRoleIdAsync(Guid userId, CancellationToken ct = default) => Set.Where(u => u.Id == userId).Select(u => u.RoleId).SingleOrDefaultAsync(ct); public Task> SearchWithRoleAsync(string? term, int? take, CancellationToken ct = default) { var query = Set.Include(u => u.Role).AsQueryable(); if (!string.IsNullOrWhiteSpace(term)) { var lower = term.Trim().ToLower(); query = query.Where(u => u.Username.ToLower().Contains(lower) || u.DisplayName.ToLower().Contains(lower)); } query = query.OrderBy(u => u.DisplayName); if (take is { } n) { query = query.Take(n); } return query.ToListAsync(ct); } }