diff --git a/src/core/DigitalData.MessagingService.Application/EmailReceiving/Queries/FetchEmailUidsQuery.cs b/src/core/DigitalData.MessagingService.Application/EmailReceiving/Queries/FetchEmailUidsQuery.cs new file mode 100644 index 0000000..7c1d92b --- /dev/null +++ b/src/core/DigitalData.MessagingService.Application/EmailReceiving/Queries/FetchEmailUidsQuery.cs @@ -0,0 +1,42 @@ +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 only the UIDs of matching emails from an IMAP mailbox. +/// +public record FetchEmailUidsQuery : 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 FetchEmailUidsQueryHandler(ISender Sender, IImapEmailService ImapService) : IRequestHandler> +{ + public async Task> Handle(FetchEmailUidsQuery 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.FetchEmailUidsAsync( + account, + request.Mail, + cancellationToken); + } +}