using DigitalData.Core.Abstraction.Application.Repository;
using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
namespace EnvelopeGenerator.Application.DocStatus.Commands;
///
/// Represents a command to save the status of a document, either by creating a new status or updating an existing one based on the provided envelope and receiver identifiers.
/// It returns the identifier of the saved document status.
///
public record SaveDocStatusCommand : ModifyDocStatusCommandBase, IRequest;
///
///
///
public static class Extensions
{
///
///
///
///
///
///
///
///
///
public static Task SignDocAsync(this IMediator mediator, string uuid, string signature, string value, CancellationToken cancel = default)
=> mediator.Send(new SaveDocStatusCommand()
{
Envelope = new() { Uuid = uuid },
Receiver = new() { Signature = signature },
Value = value
}, cancel);
}
///
///
///
public class SaveDocStatusCommandHandler : IRequestHandler
{
private readonly IRepository _repo;
///
///
///
///
public SaveDocStatusCommandHandler(IRepository repo)
{
_repo = repo;
}
///
///
///
///
///
///
public async Task Handle(SaveDocStatusCommand request, CancellationToken cancel)
{
// envelope filter
Expression>? eExp =
request.Envelope.Id is not null
? ds => ds.EnvelopeId == request.Envelope.Id
: !string.IsNullOrWhiteSpace(request.Envelope.Uuid)
? ds => ds.Envelope.Uuid == request.Envelope.Uuid
: throw new BadRequestException();
// receiver filter
Expression>? rExp =
request.Receiver.Id is not null
? ds => ds.ReceiverId == request.Receiver.Id
: request.Receiver.EmailAddress is not null
? ds => ds.Receiver.EmailAddress == request.Receiver.EmailAddress
: !string.IsNullOrWhiteSpace(request.Receiver.Signature) ? ds => ds.Receiver.Signature == request.Receiver.Signature
: throw new BadRequestException();
// ceck if exists
bool isExists = await _repo.ReadOnly().Where(eExp).Where(rExp).AnyAsync(cancel);
if (isExists)
{
var uReq = request.To();
await _repo.UpdateAsync(uReq, q => q.Where(eExp).Where(rExp), cancel);
}
else
{
var cReq = request.To();
await _repo.CreateAsync(cReq, cancel);
}
var docStatus = await _repo.ReadOnly().Where(eExp).Where(rExp).FirstOrDefaultAsync(cancel);
return docStatus?.Id;
}
}