using AutoMapper;
using AutoMapper.QueryableExtensions;
using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Application.Common.Dto;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace EnvelopeGenerator.Application.Documents.Queries;
///
/// Represents a query to read document metadata/details without binary payload.
///
/// The identifier of the envelope associated with the document.
/// The unique identifier of the sending user. Optional.
public record ReadDocumentDetailsQuery(int EnvelopeId, int? UserId = null) : IRequest;
///
/// Handles queries for reading document details without loading BYTE_DATA.
///
public class ReadDocumentDetailsQueryHandler : IRequestHandler
{
private readonly IRepository _repo;
private readonly IMapper _mapper;
public ReadDocumentDetailsQueryHandler(IRepository repo, IMapper mapper)
{
_repo = repo;
_mapper = mapper;
}
public async Task Handle(ReadDocumentDetailsQuery query, CancellationToken cancel)
{
var docQuery = _repo.Query.AsNoTracking();
if (query.UserId is int userId)
docQuery = docQuery.Where(doc => doc.Envelope.UserId == userId);
return await docQuery
.Where(d => d.EnvelopeId == query.EnvelopeId)
.ProjectTo(_mapper.ConfigurationProvider)
.FirstOrDefaultAsync(cancel);
}
}