using BCards.Web.Models; using MongoDB.Driver; namespace BCards.Web.Repositories; public class UserRepository : IUserRepository { private readonly IMongoCollection _users; public UserRepository(IMongoDatabase database) { _users = database.GetCollection("users"); // Create indexes var indexKeys = Builders.IndexKeys.Ascending(x => x.Email); var indexOptions = new CreateIndexOptions { Unique = true }; _users.Indexes.CreateOneAsync(new CreateIndexModel(indexKeys, indexOptions)); } public async Task GetByIdAsync(string id) { return await _users.Find(x => x.Id == id && x.IsActive).FirstOrDefaultAsync(); } public async Task GetByEmailAsync(string email) { return await _users.Find(x => x.Email == email && x.IsActive).FirstOrDefaultAsync(); } public async Task CreateAsync(User user) { user.CreatedAt = DateTime.UtcNow; user.UpdatedAt = DateTime.UtcNow; await _users.InsertOneAsync(user); return user; } public async Task UpdateAsync(User user) { user.UpdatedAt = DateTime.UtcNow; await _users.ReplaceOneAsync(x => x.Id == user.Id, user); return user; } public async Task DeleteAsync(string id) { await _users.UpdateOneAsync( x => x.Id == id, Builders.Update.Set(x => x.IsActive, false).Set(x => x.UpdatedAt, DateTime.UtcNow) ); } public async Task ExistsAsync(string email) { return await _users.Find(x => x.Email == email && x.IsActive).AnyAsync(); } }