using Dapper; using DigitalData.UserManager.Application.Contracts.Repositories; using EnvelopeGenerator.Application.Contracts.Repositories; using EnvelopeGenerator.Application.Contracts.SQLExecutor; using EnvelopeGenerator.Application.SQL; using EnvelopeGenerator.Domain.Entities; using Microsoft.Data.SqlClient; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace EnvelopeGenerator.Infrastructure.Executor; public class EnvelopeExecutor : SQLExecutor, IEnvelopeExecutor { private readonly IEnvelopeRepository _envelopeRepository; public EnvelopeExecutor(IServiceProvider provider, IOptions sqlExecutorParamsOptions, IEnvelopeRepository envelopeRepository) : base(provider, sqlExecutorParamsOptions) { _envelopeRepository = envelopeRepository; } public async Task CreateEnvelopeAsync(int userId, string title = "", string message = "", bool tfaEnabled = false, CancellationToken cancellation = default) { using var connection = new SqlConnection(Params.ConnectionString); var sql = Provider.GetRequiredService(); await connection.OpenAsync(cancellation); var parameters = EnvelopeCreateReadSQL.CreateParmas(userId, title, message, tfaEnabled); var envelopes = await connection.QueryAsync(sql.Raw, parameters); var envelope = envelopes.FirstOrDefault() ?? throw new InvalidOperationException($"Envelope creation failed. Parameters:" + $"userId={userId}, title='{title}', message='{message}', tfaEnabled={tfaEnabled}."); ; return await _envelopeRepository.ReadByUuidAsync(envelope.Uuid, withAll: true) ?? throw new InvalidOperationException($"Envelope creation succeeded but retrieval failed. Parameters:" + $"userId={userId}, title='{title}', message='{message}', tfaEnabled={tfaEnabled}."); } }