using System.Data; using Dapper; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using PruebaGentle.Core.Entities; using PruebaGentle.Core.Interfaces; namespace PruebaGentle.Infrastructure.Repositories; public class UserRepository : IUserRepository { private readonly string _connectionString; public UserRepository(IConfiguration configuration) { _connectionString = configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); } private IDbConnection CreateConnection() => new SqlConnection(_connectionString); public async Task CreateAsync(User user) { using var connection = CreateConnection(); var result = await connection.QuerySingleAsync( "sp_User_Create", new { user.Username, user.PasswordHash, user.Email, user.NombreCompleto }, commandType: CommandType.StoredProcedure); return result; } public async Task GetByIdAsync(int id) { using var connection = CreateConnection(); return await connection.QuerySingleOrDefaultAsync( "sp_User_GetById", new { Id = id }, commandType: CommandType.StoredProcedure); } public async Task> GetAllAsync() { using var connection = CreateConnection(); return await connection.QueryAsync( "sp_User_GetAll", commandType: CommandType.StoredProcedure); } public async Task UpdateAsync(User user) { using var connection = CreateConnection(); return await connection.QuerySingleOrDefaultAsync( "sp_User_Update", new { user.Id, user.Username, user.Email, user.NombreCompleto }, commandType: CommandType.StoredProcedure); } public async Task DeleteAsync(int id) { using var connection = CreateConnection(); var affected = await connection.ExecuteAsync( "sp_User_Delete", new { Id = id }, commandType: CommandType.StoredProcedure); return affected > 0; } public async Task GetByUsernameAsync(string username) { using var connection = CreateConnection(); return await connection.QuerySingleOrDefaultAsync( "sp_User_GetByUsername", new { Username = username }, commandType: CommandType.StoredProcedure); } }