using DigitalData.Core.Abstraction.Application.Repository;
using MediatR;
using EnvelopeGenerator.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using AutoMapper;
using EnvelopeGenerator.Application.Common.Dto;
namespace EnvelopeGenerator.Application.Documents.Queries;
///
/// Represents a query to read a document based on its unique identifier or associated envelope identifier.
///
/// The unique identifier of the document. Optional.
/// The identifier of the envelope associated with the document. Optional.
public record ReadDocumentQuery(int? Id = null, int? EnvelopeId = null) : IRequest
{
}
///
/// Handles queries for reading data based on either the document ID or the envelope ID.
///
public class ReadDocumentQueryHandler : IRequestHandler
{
///
/// TempRepo for accessing entities.
///
private readonly IRepository _repo;
private readonly IMapper _mapper;
///
/// Initializes a new instance of the class.
///
/// The repository used to access entities.
///
public ReadDocumentQueryHandler(IRepository envelopeDocumentRepository, IMapper mapper)
{
_repo = envelopeDocumentRepository;
_mapper = mapper;
}
///
/// Handles the and returns a based on the provided identifiers.
///
/// The query containing the document ID or envelope ID to search for.
/// A token to monitor for cancellation requests.
///
/// A if a matching document is found; otherwise, null.
///
///
/// Thrown when neither nor is provided.
///
public async Task Handle(ReadDocumentQuery query, CancellationToken cancel)
{
if (query.Id is not null)
{
var doc = await _repo.ReadOnly().Where(d => d.Id == query.Id).FirstOrDefaultAsync(cancel);
return _mapper.Map(doc);
}
else if (query.EnvelopeId is not null)
{
var doc = await _repo.ReadOnly().Where(d => d.EnvelopeId == query.EnvelopeId).FirstOrDefaultAsync(cancel);
return _mapper.Map(doc);
}
throw new InvalidOperationException(
$"Invalid {nameof(ReadDocumentQuery)}: either {nameof(query.Id)} or {nameof(query.EnvelopeId)} must be provided.");
}
}