using AutoMapper;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Dto.Receiver;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;
namespace EnvelopeGenerator.Application.Receivers.Commands;
///
///
///
[ApiExplorerSettings(IgnoreApi = true)]
public record CreateReceiverCommand : IRequest<(ReceiverDto Receiver, bool AlreadyExists)>
{
///
///
///
[EmailAddress]
public required string EmailAddress { get; init; }
///
///
///
public string? TotpSecretkey { get; init; }
///
/// var bytes_arr = Encoding.UTF8.GetBytes(EmailAddress.ToUpper());
/// var hash_arr = SHA256.HashData(bytes_arr);
/// var hexa_str = BitConverter.ToString(hash_arr);
/// return hexa_str.Replace("-", string.Empty);
///
public string Signature
{
get
{
var bytes_arr = Encoding.UTF8.GetBytes(EmailAddress!.ToUpper());
var hash_arr = SHA256.HashData(bytes_arr);
var hexa_str = BitConverter.ToString(hash_arr);
return hexa_str.Replace("-", string.Empty);
}
}
///
/// Default value is DateTime.Now
///
public DateTime AddedWhen { get; } = DateTime.Now;
};
///
///
///
public class CreateReceiverCommandHandler : IRequestHandler
{
///
///
///
private readonly IRepository _repo;
private readonly IMapper _mapper;
///
///
///
///
public CreateReceiverCommandHandler(IRepository repo, IMapper mapper)
{
_repo = repo;
_mapper = mapper;
}
///
///
///
///
///
///
public async Task<(ReceiverDto Receiver, bool AlreadyExists)> Handle(CreateReceiverCommand request, CancellationToken cancel)
{
var receiver = await _repo.ReadOnly()
.Where(r => r.EmailAddress == request.EmailAddress)
.SingleOrDefaultAsync(cancel);
var alreadyExists = receiver is not null;
if (!alreadyExists)
receiver = await _repo.CreateAsync(request, cancel);
var receiverDto = _mapper.Map(receiver);
return (receiverDto, alreadyExists);
}
}