using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using EnvelopeGenerator.Application.Extensions;
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)
{
// ceck if exists
bool isExists = await _repo.ReadOnly().Where(request).AnyAsync(cancel);
if (isExists)
{
var uReq = request.To();
await _repo.UpdateAsync(uReq, q => q.Where(request), cancel);
}
else
{
var cReq = request.To();
await _repo.CreateAsync(cReq, cancel);
}
var docStatus = await _repo.ReadOnly().Where(request).SingleOrDefaultAsync(cancel);
return docStatus?.Id;
}
}