using System.Data.Common; using Dapper; using Database.Connection; using Domain.Entities; using Domain.Exceptions; namespace Features.UserManagement.Repository; /// /// Dapper-based implementation of . /// public class UserAccountRepository(ISqlConnectionFactory connectionFactory) : DapperRepository(connectionFactory), IUserAccountRepository { /// public async Task GetByIdAsync(Guid id) { await using DbConnection connection = await CreateConnection(); return await connection.QueryFirstOrDefaultAsync( """ SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion FROM dbo.UserAccount WHERE UserAccountID = @UserAccountId """, new { UserAccountId = id } ); } /// /// /// Always applies pagination via OFFSET/FETCH, ordered by creation date descending. /// A null / is treated as "no limit"/"no offset". /// public async Task> GetAllAsync(int? limit, int? offset) { await using DbConnection connection = await CreateConnection(); return await connection.QueryAsync( """ SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion FROM dbo.UserAccount ORDER BY CreatedAt DESC OFFSET @Offset ROWS FETCH NEXT @Limit ROWS ONLY """, new { Offset = offset ?? 0, Limit = limit ?? int.MaxValue } ); } /// public async Task UpdateAsync(UserAccount userAccount) { await using DbConnection connection = await CreateConnection(); int rows = await connection.ExecuteAsync( """ UPDATE dbo.UserAccount SET Username = @Username, FirstName = @FirstName, LastName = @LastName, DateOfBirth = @DateOfBirth, Email = @Email WHERE UserAccountId = @UserAccountId """, new { userAccount.UserAccountId, userAccount.Username, userAccount.FirstName, userAccount.LastName, userAccount.DateOfBirth, userAccount.Email, } ); if (rows == 0) throw new NotFoundException("User account not found."); } /// public async Task DeleteAsync(Guid id) { await using DbConnection connection = await CreateConnection(); int rows = await connection.ExecuteAsync( """ DELETE FROM dbo.UserAccount WHERE UserAccountId = @UserAccountId """, new { UserAccountId = id } ); if (rows == 0) throw new NotFoundException("User account not found."); } /// public async Task GetByUsernameAsync(string username) { await using DbConnection connection = await CreateConnection(); return await connection.QueryFirstOrDefaultAsync( """ SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion FROM dbo.UserAccount WHERE Username = @Username """, new { Username = username } ); } /// public async Task GetByEmailAsync(string email) { await using DbConnection connection = await CreateConnection(); return await connection.QueryFirstOrDefaultAsync( """ SELECT UserAccountID, Username, FirstName, LastName, Email, CreatedAt, UpdatedAt, DateOfBirth, RowVersion FROM dbo.UserAccount WHERE Email = @Email """, new { Email = email } ); } }