using JobTrackerApi.Services;

namespace JobTrackerApi.Services.EmailProviders
{
    /// <summary>
    /// Generic IMAP implementation of <see cref="IEmailProvider"/> for mailboxes with no
    /// dedicated OAuth provider. Adapts <see cref="IImapService"/> to the provider-neutral
    /// contract, mapping IMAP DTOs to the neutral shapes.
    /// </summary>
    public sealed class ImapProvider : IEmailProvider
    {
        private readonly IImapService _imap;

        public ImapProvider(IImapService imap)
        {
            _imap = imap;
        }

        public string ProviderKey => "imap";

        public async Task<EmailConnectionInfo?> GetConnectionAsync(string ownerUserId, CancellationToken cancellationToken)
        {
            var connection = await _imap.GetConnectionAsync(ownerUserId, cancellationToken);
            return connection is null ? null : new EmailConnectionInfo("imap", connection.Username ?? "");
        }

        public async Task<IReadOnlyList<EmailMessageSummary>> SearchAsync(string ownerUserId, string? query, int maxResults, CancellationToken cancellationToken)
        {
            var messages = await _imap.ListMessagesAsync(ownerUserId, query, maxResults, cancellationToken);
            return messages.Select(ToSummary).ToList();
        }

        public async Task<IReadOnlyList<EmailMessageSummary>> ListThreadMessagesAsync(string ownerUserId, string threadId, CancellationToken cancellationToken)
        {
            var messages = await _imap.ListThreadMessagesAsync(ownerUserId, threadId, cancellationToken);
            return messages.Select(ToSummary).ToList();
        }

        public async Task<EmailMessageDetail> GetMessageAsync(string ownerUserId, string messageId, CancellationToken cancellationToken)
        {
            var detail = await _imap.GetMessageAsync(ownerUserId, messageId, cancellationToken);
            var attachments = detail.Attachments
                .Select(a => new EmailAttachmentRef(a.FileName, a.MimeType, a.SizeBytes, a.ContentId, a.Inline))
                .ToList();

            return new EmailMessageDetail(
                detail.Id,
                detail.ThreadKey,
                detail.Subject,
                detail.From,
                detail.To,
                detail.Date,
                detail.Snippet,
                detail.BodyText,
                detail.BodyHtml,
                detail.Labels,
                attachments);
        }

        public Task<EmailDeliveryResult> SendAsync(string ownerUserId, EmailDeliveryRequest request, CancellationToken cancellationToken) =>
            throw new EmailProviderDeliveryException("unsupported_provider", false, "This IMAP connection does not include an outgoing-mail transport.");

        private static EmailMessageSummary ToSummary(ImapMessageSummary m)
            => new(m.Id, m.ThreadKey, m.Subject, m.From, m.To, m.Date, m.Snippet);
    }
}
