using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Common.Dto.EnvelopeReceiver;
using EnvelopeGenerator.Application.Common.Extensions;
using EnvelopeGenerator.Application.DocReceiverElements.Commands;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.DocReceiverElements.Behaviors;
///
/// Pipeline behavior that resolves and validates EnvelopeReceiver.
/// Executes FIRST in the signing process - before all other behaviors.
/// If EnvelopeReceiver is not provided, it queries the database using EnvelopeReceiverQueryBase parameters.
///
public class EnvelopeReceiverResolutionBehavior : IPipelineBehavior
{
private readonly IRepository _erRepo;
private readonly IMapper _mapper;
///
///
///
///
///
public EnvelopeReceiverResolutionBehavior(IRepository erRepo, IMapper mapper)
{
_erRepo = erRepo;
_mapper = mapper;
}
///
///
///
///
///
///
///
public async Task Handle(SigningCommand request, RequestHandlerDelegate next, CancellationToken cancellationToken)
{
// If EnvelopeReceiver is not provided, query it from database
if (request.EnvelopeReceiver is null)
{
var er = await _erRepo.Query.Where(request, notnull: true).SingleOrDefaultAsync(cancellationToken)
?? throw new NotFoundException("EnvelopeReceiver not found");
request.SetEnvelopeReceiver(_mapper.Map(er));
}
return await next(cancellationToken);
}
}