using Dapper; using Shogi.Api.Repositories.Dto; using Shogi.Contracts.Api; using Shogi.Domain.Aggregates; using System.Data; using System.Data.SqlClient; namespace Shogi.Api.Repositories; public class SessionRepository(IConfiguration configuration) { private readonly string connectionString = configuration.GetConnectionString("ShogiDatabase") ?? throw new InvalidOperationException("Database connection string not configured."); public async Task CreateSession(Session session) { using var connection = new SqlConnection(this.connectionString); await connection.ExecuteAsync( "session.CreateSession", new { session.Id, Player1Id = session.Player1, }, commandType: CommandType.StoredProcedure); } public async Task DeleteSession(string id) { using var connection = new SqlConnection(this.connectionString); await connection.ExecuteAsync( "session.DeleteSession", new { Id = id }, commandType: CommandType.StoredProcedure); } public async Task<(SessionDto? Session, IEnumerable Moves)> ReadSessionAndMoves(string id) { using var connection = new SqlConnection(this.connectionString); var results = await connection.QueryMultipleAsync( "session.ReadSession", new { Id = id }, commandType: CommandType.StoredProcedure); var sessionDtos = await results.ReadAsync(); if (!sessionDtos.Any()) { return (null, []); } var moveDtos = await results.ReadAsync(); return new(sessionDtos.First(), moveDtos); } public async Task CreateMove(string sessionId, MovePieceCommand command) { using var connection = new SqlConnection(this.connectionString); await connection.ExecuteAsync( "session.CreateMove", new { command.To, command.From, command.IsPromotion, PieceFromHand = command.PieceFromHand.ToString(), SessionId = sessionId }, commandType: CommandType.StoredProcedure); } public async Task SetPlayer2(string sessionId, string player2Id) { using var connection = new SqlConnection(this.connectionString); await connection.ExecuteAsync( "session.SetPlayer2", new { SessionId = sessionId, PlayerId = player2Id }, commandType: CommandType.StoredProcedure); } }