using JobTrackerApi.Services;

namespace JobTrackerApi.Services.EmailProviders
{
    /// <summary>
    /// Gmail implementation of <see cref="IEmailProvider"/>. Adapts the existing
    /// <see cref="IGmailOAuthService"/> (Gmail REST client) to the provider-neutral contract,
    /// mapping Gmail DTOs to the neutral shapes.
    /// </summary>
    public sealed class GmailProvider : IEmailProvider
    {
        private readonly IGmailOAuthService _gmail;

        public GmailProvider(IGmailOAuthService gmail)
        {
            _gmail = gmail;
        }

        public string ProviderKey => "gmail";

        public async Task<EmailConnectionInfo?> GetConnectionAsync(string ownerUserId, CancellationToken cancellationToken)
        {
            var connection = await _gmail.GetConnectionAsync(ownerUserId, cancellationToken);
            return connection is null ? null : new EmailConnectionInfo("gmail", connection.GmailAddress ?? "", GmailOAuthService.HasSendScope(connection.Scope));
        }

        public async Task<IReadOnlyList<EmailMessageSummary>> SearchAsync(string ownerUserId, string? query, int maxResults, CancellationToken cancellationToken)
        {
            var messages = await _gmail.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 _gmail.ListThreadMessagesAsync(ownerUserId, threadId, cancellationToken);
            return messages.Select(ToSummary).ToList();
        }

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

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

        public async Task<EmailDeliveryResult> SendAsync(string ownerUserId, EmailDeliveryRequest request, CancellationToken cancellationToken)
        {
            var result = await _gmail.SendAsync(ownerUserId, new GmailSendRequest(request.To, request.Subject, request.BodyText, request.ThreadId), cancellationToken);
            return new EmailDeliveryResult(result.MessageId, result.ThreadId);
        }

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