using DigitalData.MessagingService.Abstraction; using DigitalData.MessagingService.Application.Common.Interfaces; using DigitalData.MessagingService.Application.Common.Models.MailSearch; using DigitalData.MessagingService.Application.EmailAccount.Queries; using DigitalData.MessagingService.Domain.Exceptions; using MediatR; namespace DigitalData.MessagingService.Application.EmailReceiving.Queries; /// /// Query to fetch emails from an IMAP mailbox. /// public record FetchEmailsQuery : IRequest> { /// /// Identifies the email account to use. /// public required GetSenderQuery Account { get; init; } /// /// Mail query used to filter and limit the emails retrieved. /// public MailSearchFilter Mail { get; init; } = new(); } public class FetchEmailsQueryHandler( ISender Sender, IImapEmailService ImapService) : IRequestHandler> { public async Task> Handle(FetchEmailsQuery request, CancellationToken cancellationToken) { var account = await Sender.Send(request.Account, cancellationToken) ?? throw new NotFoundException( $"No email account found for the given criteria (Id: {request.Account.Id}, Username: {request.Account.Username})."); if (string.IsNullOrWhiteSpace(account.ImapServer)) throw new InvalidOperationException( $"IMAP is not configured for account '{account.Username}' (Id: {account.Id}). Set ImapServer in EmailAccounts configuration."); return await ImapService.FetchEmailsAsync( account, request.Mail, cancellationToken); } }