Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

55.8 KB
Raw Blame
use crate::domain::models::{
    Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,
    CreatedDraft, DeletedUserDraft, DraftDeletion, EmailErr, EmailFilter, EmailInboxDetails,
    EmailThreadMailProjection, EmailThreadMetadata, EmailThreadPreview, EnrichedEmailThreadPreview,
    GetEmailsRequest, Label, Link, LinkLabel, Message, MessageAttachment, MessageLabel, MessageRow,
    MessageTimestamps, ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery,
    RecipientType, ResolvedDraftInput, ResolvedSendingInbox, SavedUserDraft, SenderPolicy,
    SendingInboxRequest, SetThreadsArchivedResult, SettledDraftIds, SimpleMessage,
    SimpleMessageInfo, SourcedAttachment, StagedLabelChange, Thread, ThreadRow,
    UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts, UserEmailLink,
    UserProvider,
};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use uuid::Uuid;

/// Keyed map of message recipients grouped by message ID.
pub type RecipientsByMessageId = HashMap<Uuid, Vec<(ContactInfo, RecipientType)>>;

/// Port for enqueuing email messages to be sent on a schedule.
pub trait EmailMessageEnqueuer: Send + Sync + 'static {
    /// Error type for enqueue operations.
    type Err: Send;

    /// Most messages one Gmail label write carries as a single provider
    /// request; a larger write is split across several queue messages.
    const MAX_LABEL_WRITE_MESSAGES: usize;

    /// Enqueue a message to be sent after an optional delay.
    fn enqueue_scheduled_message(
        &self,
        link_id: Uuid,
        message_id: Uuid,
        delay_seconds: Option<i32>,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Enqueue a batch of Gmail label modification operations to the gmail_ops worker queue.
    /// Each operation clears its message's `pending_write_id` marker when it finishes.
    fn enqueue_gmail_ops_modify_labels_batch(
        &self,
        link_id: Uuid,
        messages: Vec<(Uuid, String)>,
        labels_to_add: Vec<String>,
        labels_to_remove: Vec<String>,
        pending_write_id: Uuid,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Enqueue a Gmail-ops BlockSender operation for the link.
    fn enqueue_gmail_ops_block_sender(
        &self,
        link_id: Uuid,
        email_address: String,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Enqueue a Gmail-ops UnblockSender operation for the link.
    fn enqueue_gmail_ops_unblock_sender(
        &self,
        link_id: Uuid,
        email_address: String,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}

/// The sending inbox's signature preferences, used by the send pipeline to
/// decide whether to inject the signature into the outgoing body.
#[derive(Debug, Clone, Default)]
pub struct LinkEmailSettings {
    /// The saved signature HTML (already sanitized server-side), if any.
    pub signature: Option<String>,
    /// Whether the signature should be added on replies and forwards.
    pub signature_on_replies_forwards: bool,
}

/// Outbound repository capabilities for authenticated user email catalogs.
///
/// The port returns persisted facts only. Accessible-inbox aggregation and
/// synchronization-status policy remain in the email domain service.
pub trait EmailUserRepo: Send + Sync + 'static {
    /// Sender rules for an inbox already authorized by the user service.
    fn user_sender_filters(
        &self,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<EmailFilter>, EmailErr>> + Send;
    /// Resolve every owned or delegated inbox accessible to `macro_id`.
    fn user_accessible_inboxes(
        &self,
        macro_id: MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;

    /// Fetch all labels belonging to one already-authorized inbox.
    fn user_labels_for_link(
        &self,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<LinkLabel>, EmailErr>> + Send;

    /// Fetch enriched persisted facts for every owned or delegated inbox.
    fn user_inbox_details(
        &self,
        macro_id: MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<Vec<EmailInboxDetails>, EmailErr>> + Send;
}

pub trait EmailRepo: Send + Sync + 'static {
    /// Latest durable command per organization attribute in an authorized thread.
    fn thread_mailbox_operations(
        &self,
        _link: Uuid,
        _thread: Uuid,
    ) -> impl Future<
        Output = Result<Vec<super::models::mailbox_action::MailboxOperation>, Self::Err>,
    > + Send {
        async { Ok(Vec::new()) }
    }

    /// Revalidate inbox access and persist sender intent and classification atomically.
    fn commit_sender_policy(
        &self,
        actor: &MacroUserIdStr<'_>,
        link: Uuid,
        sender: &str,
        blocked: bool,
        important: Option<bool>,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Revalidate actor and expected facts while committing a user-directed resolution.
    fn commit_message_resolution(
        &self,
        actor: &MacroUserIdStr<'_>,
        plan: super::models::mailbox_operation::MessageResolutionPlan,
    ) -> impl Future<Output = Result<Uuid, EmailErr>> + Send;
    /// Durable write facts for a batch of already-authorized messages.
    fn message_operation_facts(
        &self,
        ids: &[Uuid],
    ) -> impl Future<
        Output = Result<
            HashMap<Uuid, super::models::mailbox_operation::MessageOperationFacts>,
            Self::Err,
        >,
    > + Send;
    type Err: Send;
    /// Read message organization facts within an already-authorized inbox.
    fn mailbox_action_messages(
        &self,
        link_id: Uuid,
        thread_id: Uuid,
    ) -> impl Future<
        Output = Result<
            Vec<crate::domain::models::mailbox_action::MailboxActionMessage>,
            Self::Err,
        >,
    > + Send;
    /// Persist frozen targets, pending state and a durable command atomically.
    fn enqueue_mailbox_action(
        &self,
        link_id: Uuid,
        actor: MacroUserIdStr<'_>,
        action: &crate::domain::models::mailbox_action::MailboxAction,
        targets: &[crate::domain::models::mailbox_action::MailboxActionTarget],
    ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;
    fn previews_for_view_cursor(
        &self,
        query: PreviewCursorQuery,
        user_id: MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<Vec<EmailThreadPreview>, Self::Err>> + Send;

    fn attachments_by_thread_ids(
        &self,
        thread_ids: &[Uuid],
    ) -> impl Future<Output = Result<Vec<Attachment>, Self::Err>> + Send;

    fn contacts_by_thread_ids(
        &self,
        thread_ids: &[Uuid],
    ) -> impl Future<Output = Result<Vec<Contact>, Self::Err>> + Send;

    fn labels_by_thread_ids(
        &self,
        thread_ids: &[Uuid],
    ) -> impl Future<Output = Result<Vec<Label>, Self::Err>> + Send;

    fn link_by_fusionauth_and_macro_id(
        &self,
        fusionauth_user_id: &str,
        macro_id: MacroUserIdStr<'_>,
        provider: UserProvider,
    ) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;

    /// Resolve the inbox owning a thread, only when that inbox belongs to the
    /// given fusionauth user.
    fn owned_link_for_thread(
        &self,
        thread_id: Uuid,
        macro_id: MacroUserIdStr<'_>,
    ) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;

    /// Returns every inbox accessible to `macro_id`: their own email_links plus
    /// any reachable via a `macro_user_links` edge (narrow-graph multi-inbox).
    fn inboxes_for_macro_id(
        &self,
        macro_id: MacroUserIdStr<'_>,
    ) -> impl Future<Output = Result<Vec<Link>, Self::Err>> + Send;

    /// Fetch a thread by its database ID (without messages).
    fn thread_by_id(
        &self,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<Option<ThreadRow>, Self::Err>> + Send;

    /// Fetch canonical metadata for a batch of thread IDs.
    fn thread_metadata_by_ids(
        &self,
        thread_ids: &[Uuid],
    ) -> impl Future<Output = Result<Vec<EmailThreadMetadata>, Self::Err>> + Send;

    /// Fetch Mail-specific cache facts and previews for a batch of thread IDs.
    fn thread_mail_projections_by_ids(
        &self,
        viewer: MacroUserIdStr<'_>,
        thread_ids: &[Uuid],
    ) -> impl Future<Output = Result<Vec<EmailThreadMailProjection>, Self::Err>> + Send;

    /// Fetch paginated messages for a thread, ordered by internal_date_ts descending.
    fn messages_by_thread_id_paginated(
        &self,
        thread_id: Uuid,
        offset: i64,
        limit: i64,
    ) -> impl Future<Output = Result<Vec<MessageRow>, Self::Err>> + Send;

    /// Fetch the newest non-draft content message for each requested thread.
    fn latest_content_message_rows(
        &self,
        thread_ids: &[Uuid],
    ) -> impl Future<Output = Result<Vec<MessageRow>, Self::Err>> + Send;

    /// Find macro reply drafts (across the given inboxes) that reply to any of
    /// `replying_to_ids` but live in a thread other than `exclude_thread_id` —
    /// i.e. a reply moved to another inbox by switching the sender.
    fn cross_inbox_reply_drafts(
        &self,
        replying_to_ids: &[Uuid],
        link_ids: &[Uuid],
        exclude_thread_id: Uuid,
    ) -> impl Future<Output = Result<Vec<MessageRow>, Self::Err>> + Send;

    /// Fetch sender contact info for a set of message IDs, keyed by message ID.
    fn senders_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<HashMap<Uuid, ContactInfo>, Self::Err>> + Send;

    /// Fetch recipient contact info for a set of message IDs, keyed by message ID.
    fn recipients_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<RecipientsByMessageId, Self::Err>> + Send;

    /// Fetch labels for a set of message IDs, keyed by message ID.
    fn labels_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<HashMap<Uuid, Vec<MessageLabel>>, Self::Err>> + Send;

    /// Fetch saved calendar invitation components, keyed by message ID.
    fn calendar_invitations_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<
        Output = Result<
            HashMap<Uuid, Vec<crate::domain::models::calendar_invitation::CalendarInvitation>>,
            Self::Err,
        >,
    > + Send;

    /// Fetch persisted message timestamps, scoped to the sending inbox.
    fn message_timestamps(
        &self,
        message_id: Uuid,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Option<MessageTimestamps>, Self::Err>> + Send;

    /// Fetch provider attachments for a set of message IDs, keyed by message ID.
    fn attachments_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err>> + Send;

    /// Fetch draft attachments for a set of message IDs, keyed by message ID.
    fn draft_attachments_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<HashMap<Uuid, Vec<AttachmentDraft>>, Self::Err>> + Send;

    /// Fetch forwarded attachments for a set of message IDs, keyed by message ID.
    fn forwarded_attachments_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<HashMap<Uuid, Vec<AttachmentForwarded>>, Self::Err>> + Send;

    /// Fetch schedule times and delivery states, keyed by message ID.
    /// Only returns entries for unsent scheduled messages.
    fn scheduled_sends_by_message_ids(
        &self,
        message_ids: &[Uuid],
    ) -> impl Future<Output = Result<HashMap<Uuid, crate::domain::models::ScheduledSend>, Self::Err>>
    + Send;

    /// Fetch a simplified message by its DB ID, scoped to a set of accessible
    /// inbox link IDs (for validation across own + delegated inboxes).
    fn get_simple_message(
        &self,
        message_id: Uuid,
        link_ids: &[Uuid],
    ) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;

    /// Resolve a client draft handle to its server-minted message ID through
    /// the mapping table, scoped to the caller's inboxes — identical handles
    /// from different users never interact.
    fn message_id_for_client_draft_id(
        &self,
        client_id: Uuid,
        link_ids: &[Uuid],
    ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;

    /// Resolve a client thread handle to its server-minted thread ID through
    /// the mapping table, scoped to the caller's inboxes.
    fn thread_id_for_client_thread_id(
        &self,
        client_id: Uuid,
        link_ids: &[Uuid],
    ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;

    /// Resolve an empty server thread to its same-inbox canonical conversation.
    /// Both identities must belong to an inbox in the caller's accessible set.
    fn redirected_thread_id(
        &self,
        thread_id: Uuid,
        link_ids: &[Uuid],
    ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;

    /// Find an existing draft that replies to the given message ID.
    fn get_draft_replying_to(
        &self,
        link_id: Uuid,
        replying_to_id: Uuid,
    ) -> impl Future<Output = Result<Option<SimpleMessageInfo>, Self::Err>> + Send;

    /// Delete a draft message and its thread if the thread is left empty.
    /// A surviving thread gets its denormalized metadata (inbox visibility,
    /// latest timestamps, is_signal) recomputed, since drafts count toward
    /// those fields.
    ///
    /// Ownership is enforced in the DELETE's WHERE clause — the row must be
    /// an unsent draft in `thread_db_id` belonging to one of `link_ids` —
    /// so a raced validation read can never delete someone else's row.
    /// Returns `None` when no row matched (already deleted, sent, or not
    /// owned): deletes are idempotent, classification is the caller's job.
    fn delete_draft_message(
        &self,
        message_id: Uuid,
        thread_db_id: Uuid,
        link_ids: &[Uuid],
        actor: Option<&str>,

        expected_generation: i32,
    ) -> impl Future<Output = Result<Option<DraftDeletion>, Self::Err>> + Send;

    /// Upsert contacts from the parsed addresses. Must be called outside a transaction
    /// to avoid deadlocks (contacts are shared across messages).
    fn upsert_contacts(
        &self,
        link_id: Uuid,
        addresses: ParsedAddresses,
    ) -> impl Future<Output = Result<UpsertedContacts, Self::Err>> + Send;

    /// Insert a message within a transaction, including thread insert (if new),
    /// recipients, thread metadata update, and user history. Ordinary drafts never
    /// schedule delivery; non-drafts may create an immediate-send undo window.
    /// Lock and re-read client-handle bindings, bind handles to the final rows,
    /// and return their authoritative IDs. Return None when an owner/sent guard
    /// rejects the write; reject scheduled/processing identities transactionally.
    /// If `new_thread` is Some, the thread is created inside the same transaction.
    fn insert_message(
        &self,
        input: &ResolvedDraftInput,
        contacts: &UpsertedContacts,
        link_id: Uuid,
        new_thread: Option<ThreadRow>,
        is_draft: bool,
    ) -> impl Future<Output = Result<Option<SettledDraftIds>, EmailErr>> + Send;

    /// Fetch a label by its database ID and link ID.
    fn get_label_by_id(
        &self,
        label_id: Uuid,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Option<LinkLabel>, Self::Err>> + Send;

    /// Fetch all messages in a thread for label operations.
    fn get_thread_label_messages(
        &self,
        thread_id: Uuid,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<SimpleMessage>, Self::Err>> + Send;

    /// Bulk insert a label for multiple messages.
    fn insert_message_labels_batch(
        &self,
        message_ids: &[Uuid],
        provider_label_id: &str,
        link_id: Uuid,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Bulk delete a label from multiple messages.
    fn delete_message_labels_batch(
        &self,
        message_ids: &[Uuid],
        provider_label_id: &str,
        link_id: Uuid,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Atomically stage a label change on an already-authorized thread for
    /// Gmail: read which messages gain or lose the label, apply the change to
    /// every message with the read, starred and inbox flags it drives, and
    /// mark the changed messages that have a provider id — exactly those a
    /// Gmail write sends — as waiting on `write_id`, so inbox sync keeps their
    /// local state until Gmail confirms it. Label writes on one thread take
    /// turns, so each reads the state the one before it left. `None`, with
    /// nothing changed, when the thread has no messages.
    fn stage_thread_label_change(
        &self,
        thread_id: Uuid,
        link_id: Uuid,
        provider_label_id: &str,
        add: bool,
        write_id: Uuid,
    ) -> impl Future<Output = Result<Option<StagedLabelChange>, Self::Err>> + Send;

    /// Atomically undo a staged label change Gmail will never receive.
    /// `provider_message_ids` go back to the state Gmail will end up with:
    /// that of the newest older write still on its way, or the one before
    /// this write; a newer write keeps its own. `local_message_ids`
    /// (Macro-only drafts) lose the change. The thread's state is derived
    /// again, all while holding the thread's label-write lock.
    #[expect(clippy::too_many_arguments, reason = "the parts of one staged change")]
    fn revert_staged_label_change(
        &self,
        thread_id: Uuid,
        link_id: Uuid,
        provider_label_id: &str,
        add: bool,
        write_id: Uuid,
        provider_message_ids: &[Uuid],
        local_message_ids: &[Uuid],
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Update the read status for a batch of messages, verified by link_id.
    fn update_message_read_status_batch(
        &self,
        message_ids: &[Uuid],
        link_id: Uuid,
        is_read: bool,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Update the denormalized thread-level read status, verified by link_id.
    fn update_thread_read_status(
        &self,
        thread_id: Uuid,
        link_id: Uuid,
        is_read: bool,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Record that the user viewed a thread.
    fn upsert_thread_user_history(
        &self,
        link_id: Uuid,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Update the starred status for a batch of messages, verified by link_id.
    fn update_message_starred_status_batch(
        &self,
        message_ids: &[Uuid],
        link_id: Uuid,
        is_starred: bool,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Fetch all labels for a link.
    fn list_labels_by_link_id(
        &self,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<LinkLabel>, Self::Err>> + Send;

    /// Cancel scheduled deliveries for currently unsent drafts under the
    /// message -> schedule lock order. Preserve submitted, unconfirmed and
    /// ambiguous legacy claims; managed preparation may be revoked before
    /// submission. Atomically retire the revoked sends' attempts so a delayed
    /// cancellation cannot affect a replacement send. Returns only the message
    /// IDs actually cancelled.
    fn delete_scheduled_messages_batch(
        &self,
        message_ids: &[Uuid],
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<Uuid>, Self::Err>> + Send;

    /// Update the project assignment for a thread. Pass `None` to remove from project.
    /// Returns `false` if the thread was not found.
    fn update_thread_project(
        &self,
        thread_id: Uuid,
        project_id: Option<&str>,
    ) -> impl Future<Output = Result<bool, Self::Err>> + Send;

    /// Get the current project_id for a thread.
    fn get_thread_project_id(
        &self,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;

    /// Advance a project's activity timestamp.
    fn touch_project_updated_at(
        &self,
        project_id: &str,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;

    /// Upsert an email filter (by address or domain) for a link.
    fn upsert_email_filter(
        &self,
        link_id: Uuid,
        input: UpsertEmailFilterInput,
    ) -> impl Future<Output = Result<EmailFilter, Self::Err>> + Send;

    /// Delete an email filter by its ID, scoped to a link.
    fn delete_email_filter(
        &self,
        filter_id: Uuid,
        link_id: Uuid,
    ) -> impl Future<Output = Result<bool, Self::Err>> + Send;

    /// List all email filters for a link.
    fn list_email_filters(
        &self,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<EmailFilter>, Self::Err>> + Send;

    /// Fetch the inbox's signature preferences. Defaults to "no signature" so
    /// repos that don't override it (and the send path when settings are
    /// missing) simply skip signature injection.
    fn fetch_email_settings(
        &self,
        _link_id: Uuid,
    ) -> impl Future<Output = Result<LinkEmailSettings, EmailErr>> + Send {
        async { Ok(LinkEmailSettings::default()) }
    }
}

/// Read-only capability for fetching email thread previews. The composition
/// root supplies the replica-backed service for ordinary REST/GraphQL Soup.
/// Mutation replies reload through the primary-backed email writer instead.
pub trait EmailPreviewServiceReadOnly: Send + Sync + 'static {
    fn get_email_thread_previews(
        &self,
        req: GetEmailsRequest,
    ) -> impl Future<
        Output = Result<
            PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>,
            EmailErr,
        >,
    > + Send;
}

/// Read-only domain service used to hydrate canonical email-thread metadata edges.
pub trait EmailThreadMetadataService: Send + Sync + 'static {
    /// Fetch canonical metadata for authorized email threads in one batch.
    fn get_email_thread_metadata(
        &self,
        receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> impl Future<Output = Result<HashMap<Uuid, EmailThreadMetadata>, EmailErr>> + Send;
}

/// Read-only domain service used to hydrate offline Mail projection data.
pub trait EmailThreadMailProjectionService: Send + Sync + 'static {
    /// Fetch cache facts and canonical previews for authorized threads in one batch.
    fn get_email_thread_mail_projections(
        &self,
        viewer: MacroUserIdStr<'static>,
        receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> impl Future<Output = Result<HashMap<Uuid, EmailThreadMailProjection>, EmailErr>> + Send;
}

/// Read-only domain service used to hydrate Soup previews of authorized threads.
pub trait EmailThreadPreviewService: Send + Sync + 'static {
    /// Fetch the Soup preview of each authorized thread in one batch, as the
    /// thread's own inbox renders it. A thread without a row is absent.
    fn get_email_thread_previews_by_receipts(
        &self,
        viewer: MacroUserIdStr<'static>,
        receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> impl Future<Output = Result<Vec<EnrichedEmailThreadPreview>, EmailErr>> + Send;
}

/// Read-only domain service used to hydrate lightweight email content edges.
pub trait EmailContentService: Send + Sync + 'static {
    /// Fetch the newest non-draft parsed content message for each authorized thread.
    fn get_latest_messages_parsed(
        &self,
        receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> impl Future<Output = Result<HashMap<Uuid, ParsedMessage>, EmailErr>> + Send;

    /// Fetch the newest non-draft fully hydrated message for each authorized thread.
    fn get_latest_messages_full(
        &self,
        receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> impl Future<Output = Result<HashMap<Uuid, Message>, EmailErr>> + Send;

    /// Fetch one page of parsed messages for an authorized thread.
    fn get_messages_parsed(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
        offset: i64,
        limit: i64,
    ) -> impl Future<Output = Result<Option<Vec<ParsedMessage>>, EmailErr>> + Send;

    /// Fetch one page of fully hydrated messages for an authorized thread.
    fn get_messages_full(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
        offset: i64,
        limit: i64,
    ) -> impl Future<Output = Result<Option<Vec<Message>>, EmailErr>> + Send;
}

/// Newtype adapter that restricts a full `EmailService` to read-only preview access.
/// This narrows capabilities, not consistency: the wrapped service may use a
/// primary or replica pool. A bare `EmailServiceImpl` will not silently satisfy
/// `EmailPreviewServiceReadOnly`.
#[derive(Clone)]
pub struct ReadonlyEmailPreviewAdapter<T>(pub T);

impl<T: EmailService> EmailPreviewServiceReadOnly for ReadonlyEmailPreviewAdapter<T> {
    fn get_email_thread_previews(
        &self,
        req: GetEmailsRequest,
    ) -> impl Future<
        Output = Result<
            PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>,
            EmailErr,
        >,
    > + Send {
        EmailService::get_email_thread_previews(&self.0, req)
    }
}

impl<T: EmailThreadPreviewService> EmailThreadPreviewService for ReadonlyEmailPreviewAdapter<T> {
    fn get_email_thread_previews_by_receipts(
        &self,
        viewer: MacroUserIdStr<'static>,
        receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> impl Future<Output = Result<Vec<EnrichedEmailThreadPreview>, EmailErr>> + Send {
        self.0
            .get_email_thread_previews_by_receipts(viewer, receipts)
    }
}

/// User-scoped read operations consumed by email inbound adapters.
pub trait EmailUserService: Send + Sync + 'static {
    /// Verified senders for an owned/delegated inbox. Authorization precedes
    /// provider access; an inaccessible inbox is indistinguishable from absent.
    fn get_user_email_senders(
        &self,
        macro_id: MacroUserIdStr<'static>,
        link_id: Uuid,
    ) -> impl Future<Output = Result<Vec<crate::domain::senders::SendAsAddress>, EmailErr>> + Send;

    /// List labels across every owned or delegated inbox accessible to the user.
    fn get_user_email_labels(
        &self,
        macro_id: MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<Vec<LinkLabel>, EmailErr>> + Send;

    /// List enriched owned or delegated email links accessible to the user.
    fn get_user_email_links(
        &self,
        macro_id: MacroUserIdStr<'static>,
    ) -> impl Future<Output = Result<Vec<UserEmailLink>, EmailErr>> + Send;
}

pub trait EmailService: Send + Sync + 'static {
    /// Organization status is visible only to current inbox members.
    fn thread_mailbox_operations(
        &self,
        _actor: MacroUserIdStr<'static>,
        _thread: Uuid,
    ) -> impl Future<Output = Result<Vec<super::models::mailbox_action::MailboxOperation>, EmailErr>>
    + Send {
        async { Err(no_op_email_err()) }
    }

    /// Load operation state only for a currently accessible inbox message.
    fn message_operation_status(
        &self,
        _actor: MacroUserIdStr<'static>,
        _message_id: Uuid,
    ) -> impl Future<
        Output = Result<Option<super::models::mailbox_operation::MessageOperationStatus>, EmailErr>,
    > + Send {
        async { Err(no_op_email_err()) }
    }

    /// Resolve a draft conflict or uncertain delivery with fresh inbox authorization.
    fn resolve_message_operation(
        &self,
        actor: MacroUserIdStr<'static>,
        request: super::models::mailbox_operation::MessageResolutionRequest,
    ) -> impl Future<Output = Result<Uuid, EmailErr>> + Send;
    /// Set semantic mailbox state without requiring a provider system-label ID.
    /// The number of the thread's messages it changed; none when they were
    /// already in that state.
    fn change_thread_mailbox_state(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _thread_id: Uuid,
        _action: crate::domain::models::mailbox_action::MailboxAction,
    ) -> impl Future<Output = Result<usize, EmailErr>> + Send {
        async { Err(no_op_email_err()) }
    }
    /// Authorize the caller's sending inbox, resolve client handles, and enqueue
    /// delivery with attribution to the authenticated actor.
    fn send_message_for_user(
        &self,
        macro_id: MacroUserIdStr<'static>,
        link_id: Option<Uuid>,
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;

    fn get_email_thread_previews(
        &self,
        req: GetEmailsRequest,
    ) -> impl Future<
        Output = Result<
            PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>,
            EmailErr,
        >,
    > + Send;

    fn get_link_by_auth_id_and_macro_id(
        &self,
        auth_id: &str,
        macro_id: MacroUserIdStr<'_>,
    ) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;

    /// Fetch every inbox the caller can read — their own email_links rows plus
    /// any rows reachable via a `macro_user_links` edge (narrow-graph multi-inbox).
    fn get_inboxes_for_macro_id(
        &self,
        macro_id: MacroUserIdStr<'_>,
    ) -> impl Future<Output = Result<Vec<Link>, EmailErr>> + Send;

    /// Resolve which inbox a composed email is sent from, for a transport
    /// that carries the inbox by value instead of out of band: the address
    /// the caller named, else the inbox that received the message being
    /// replied to, else the caller's default inbox. Returns the whole
    /// accessible set alongside it, which [`send_message`] needs anyway.
    ///
    /// [`send_message`]: EmailService::send_message
    fn resolve_sending_inbox(
        &self,
        macro_id: MacroUserIdStr<'_>,
        request: SendingInboxRequest<'_>,
    ) -> impl Future<Output = Result<ResolvedSendingInbox, EmailErr>> + Send;

    /// Resolve the inbox owning a thread, scoped to the caller's own and
    /// delegated inboxes. Lets thread-targeted mutations derive the inbox from
    /// the thread instead of an `X-Email-Link-Id` header.
    fn get_owned_link_for_thread(
        &self,
        macro_id: MacroUserIdStr<'_>,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<Option<Link>, EmailErr>> + Send;

    /// Follow an empty thread's canonical alias only within the user's inboxes.
    /// The returned thread still requires normal entity authorization at the caller.
    fn resolve_thread_read_id(
        &self,
        macro_id: MacroUserIdStr<'_>,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<Uuid, EmailErr>> + Send;

    /// Fetch a thread with paginated messages, verifying access via the provided receipt.
    fn get_thread_with_messages(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
        offset: i64,
        limit: i64,
    ) -> impl Future<Output = Result<Option<Thread>, EmailErr>> + Send;

    /// Fetch a thread with lightweight parsed messages (no attachments or scheduled send times).
    fn get_thread_parsed(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
        offset: i64,
        limit: i64,
    ) -> impl Future<Output = Result<Option<ParsedThread>, EmailErr>> + Send;

    /// Create a draft message sent from `link`. `accessible_inboxes` is every
    /// inbox the caller can reach (own + delegated); a reply target may live in
    /// any of them, not just `link`.
    fn create_draft(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;

    /// Create or update a draft for the authenticated user, resolving the
    /// sending inbox from `link_id` (or the caller's primary inbox when
    /// `None`). Lets transports without the `X-Email-Link-Id` header (the
    /// GraphQL mutation, whose offline replay persists only variables) target
    /// an inbox by value. The input's `db_id`/`thread_db_id` are client
    /// handles here — resolved through the caller-scoped mapping tables and
    /// bound to server-minted rows, never used as primary keys.
    fn save_draft_for_user(
        &self,
        macro_id: MacroUserIdStr<'_>,
        link_id: Option<Uuid>,
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<SavedUserDraft, EmailErr>> + Send;

    /// Delete a draft for the authenticated user, searching every inbox they
    /// can reach. `draft_id` is a handle resolved like a save's: through the
    /// caller-scoped mapping, else as a server ID. Idempotent: a handle that
    /// resolves to nothing (or to a row that is not theirs — reported
    /// identically to avoid an existence oracle) is a successful no-op, so a
    /// delete queued offline lands cleanly however late it replays. Deleting
    /// a draft that has since been sent fails with `MessageAlreadySent`.
    fn delete_draft_for_user(
        &self,
        macro_id: MacroUserIdStr<'_>,
        draft_id: Uuid,

        expected_generation: i32,
    ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send;

    /// Send a message: persist it and enqueue for scheduled delivery.
    /// `accessible_inboxes` is every inbox the caller can reach (own +
    /// delegated); a reply target may live in any of them, not just `link`.
    fn send_message(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;

    /// List all labels for the given link.
    fn list_labels(
        &self,
        link: &Link,
    ) -> impl Future<Output = Result<Vec<LinkLabel>, EmailErr>> + Send;

    /// Add or remove a label from all messages in a thread. Provider sync
    /// happens asynchronously via the gmail_ops queue.
    fn update_thread_labels(
        &self,
        link: &Link,
        thread_id: Uuid,
        label_id: Uuid,
        add: bool,
    ) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send;

    /// Mark a caller-accessible thread as seen and read.
    fn mark_thread_seen(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _thread_id: Uuid,
    ) -> impl Future<Output = Result<(), EmailErr>> + Send {
        async { Err(no_op_email_err()) }
    }

    /// Mark a caller-accessible thread unread using its own inbox's UNREAD label.
    /// Provider synchronization and read-state updates use the thread-label flow.
    fn mark_thread_unread(
        &self,
        macro_id: MacroUserIdStr<'static>,
        thread_id: Uuid,
    ) -> impl Future<Output = Result<(), EmailErr>> + Send;

    /// Archive or unarchive a caller-owned/delegated thread. The service
    /// resolves the thread's inbox and system label, then queues provider sync.
    fn set_thread_archived(
        &self,
        macro_id: MacroUserIdStr<'static>,
        thread_id: Uuid,
        archived: bool,
    ) -> impl Future<Output = Result<(), EmailErr>> + Send;

    /// Archive or unarchive up to [`MAX_BULK_ARCHIVE_THREADS`] caller-owned or
    /// delegated threads, queueing one provider write per inbox. Threads that
    /// can't change are reported in the result instead of failing the rest.
    ///
    /// [`MAX_BULK_ARCHIVE_THREADS`]: super::models::MAX_BULK_ARCHIVE_THREADS
    fn set_threads_archived(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _thread_ids: Vec<Uuid>,
        _archived: bool,
    ) -> impl Future<Output = Result<SetThreadsArchivedResult, EmailErr>> + Send {
        async { Err(no_op_email_err()) }
    }

    /// Add or remove a label from a caller-accessible thread.
    fn update_thread_labels_for_user(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _thread_id: Uuid,
        _label_id: Uuid,
        _add: bool,
    ) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send {
        async { Err(no_op_email_err()) }
    }

    /// Update the project assignment for a thread. Returns the old project_id.
    ///
    /// `thread_receipt` proves the caller has edit access to the thread.
    /// `project_receipt` proves the caller has edit access to the target project.
    /// Pass `None` to remove the thread from its current project.
    fn update_thread_project(
        &self,
        thread_receipt: EntityAccessReceipt<EditAccessLevel>,
        project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,
    ) -> impl Future<Output = Result<Option<String>, EmailErr>> + Send;

    /// Upsert an email filter for the given link.
    fn upsert_email_filter(
        &self,
        link: &Link,
        input: UpsertEmailFilterInput,
    ) -> impl Future<Output = Result<EmailFilter, EmailErr>> + Send;

    /// Set where future mail from a sender lands for the given inbox.
    ///
    /// Signal and Noise also enqueue an UnblockSender so a prior Block does
    /// not keep trashing new mail.
    fn set_sender_policy(
        &self,
        actor: &MacroUserIdStr<'_>,
        link: &Link,
        sender_email: &str,
        policy: SenderPolicy,
    ) -> impl Future<Output = Result<(), EmailErr>> + Send;

    /// Delete an email filter by its ID for the given link.
    fn delete_email_filter(
        &self,
        link: &Link,
        filter_id: Uuid,
    ) -> impl Future<Output = Result<bool, EmailErr>> + Send;

    /// List all email filters for the given link.
    fn list_email_filters(
        &self,
        link: &Link,
    ) -> impl Future<Output = Result<Vec<EmailFilter>, EmailErr>> + Send;
}

/// Port for fetching a Gmail access token for a given email link.
///
/// The domain service receives the token as an opaque `&str`. This trait
/// allows the toolset layer to resolve tokens without depending on axum.
pub trait GmailTokenProvider: Send + Sync + 'static {
    /// Fetch a Gmail OAuth access token for the given email link.
    fn fetch_gmail_access_token(
        &self,
        link: &Link,
    ) -> impl Future<Output = Result<String, EmailErr>> + Send;

    /// Fetch a Gmail OAuth access token directly from the auth service,
    /// bypassing the Redis cache for reads but still caching the result.
    fn fetch_gmail_access_token_no_cache(
        &self,
        link: &Link,
    ) -> impl Future<Output = Result<String, EmailErr>> + Send;
}

/// No-op token provider for callers that don't need Gmail token resolution.
#[derive(Clone)]
pub struct NoOpGmailTokenProvider;

impl GmailTokenProvider for NoOpGmailTokenProvider {
    async fn fetch_gmail_access_token(&self, _link: &Link) -> Result<String, EmailErr> {
        Err(EmailErr::ProviderErr(anyhow::anyhow!(
            "Gmail token provider not configured"
        )))
    }

    async fn fetch_gmail_access_token_no_cache(&self, _link: &Link) -> Result<String, EmailErr> {
        Err(EmailErr::ProviderErr(anyhow::anyhow!(
            "Gmail token provider not configured"
        )))
    }
}

/// Port for turning a Macro document the caller may view into the file an
/// outgoing email attaches. The email domain never reads document storage
/// itself; a composition root implements this over the documents domain.
pub trait DraftAttachmentSource: Send + Sync + 'static {
    /// Resolve the document the receipt names into its bytes, name, and
    /// MIME type. Errors with [`EmailErr::AttachmentUnavailable`] when the
    /// document has no file to attach.
    fn fetch_attachment(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> impl Future<Output = Result<SourcedAttachment, EmailErr>> + Send;
}

/// Port for the object store the scheduled sender reads draft attachments
/// from. Keys are the domain's; the adapter only owns the bucket.
pub trait DraftAttachmentStorage: Send + Sync + 'static {
    /// Store one attachment's bytes under `key`.
    fn put_attachment(
        &self,
        key: &str,
        content_type: &str,
        bytes: &[u8],
    ) -> impl Future<Output = anyhow::Result<()>> + Send;
}

/// Port for recording a staged draft attachment against its draft row.
pub trait DraftAttachmentRepo: Send + Sync + 'static {
    /// Error type for repository operations.
    type Err: Send;

    /// Record `attachment` on its draft. A draft outside `link_id` must be
    /// left untouched: the row the record points at is the sending inbox's.
    fn insert_draft_attachment(
        &self,
        link_id: Uuid,
        attachment: &AttachmentDraft,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}

impl<T: DraftAttachmentSource> DraftAttachmentSource for Arc<T> {
    fn fetch_attachment(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> impl Future<Output = Result<SourcedAttachment, EmailErr>> + Send {
        T::fetch_attachment(self, receipt)
    }
}

impl<T: DraftAttachmentStorage> DraftAttachmentStorage for Arc<T> {
    fn put_attachment(
        &self,
        key: &str,
        content_type: &str,
        bytes: &[u8],
    ) -> impl Future<Output = anyhow::Result<()>> + Send {
        T::put_attachment(self, key, content_type, bytes)
    }
}

impl<T: DraftAttachmentRepo> DraftAttachmentRepo for Arc<T> {
    type Err = T::Err;

    fn insert_draft_attachment(
        &self,
        link_id: Uuid,
        attachment: &AttachmentDraft,
    ) -> impl Future<Output = Result<(), Self::Err>> + Send {
        T::insert_draft_attachment(self, link_id, attachment)
    }
}

/// The slice of [`EmailService`] a staged send needs: save the draft, send
/// it, discard it. Every `EmailService` is one; the narrower bound lets the
/// use case be tested against a fake of three methods.
pub trait DraftSendService: Send + Sync + 'static {
    /// See [`EmailService::create_draft`].
    fn create_draft(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;

    /// See [`EmailService::send_message`].
    fn send_message(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;

    /// See [`EmailService::delete_draft_for_user`].
    fn delete_draft_for_user(
        &self,
        macro_id: MacroUserIdStr<'_>,
        draft_id: Uuid,

        expected_generation: i32,
    ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send;
}

impl<T: EmailService> DraftSendService for T {
    fn create_draft(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send {
        EmailService::create_draft(self, link, accessible_inboxes, input)
    }

    fn send_message(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send {
        EmailService::send_message(self, link, accessible_inboxes, input)
    }

    fn delete_draft_for_user(
        &self,
        macro_id: MacroUserIdStr<'_>,
        draft_id: Uuid,

        expected_generation: i32,
    ) -> impl Future<Output = Result<DeletedUserDraft, EmailErr>> + Send {
        EmailService::delete_draft_for_user(self, macro_id, draft_id, expected_generation)
    }
}

/// Narrow port choosing the inbox a composed email is sent from, for use
/// cases that need nothing else of the [`EmailService`].
pub trait SendingInboxResolver: Send + Sync + 'static {
    /// See [`EmailService::resolve_sending_inbox`].
    fn resolve_sending_inbox(
        &self,
        macro_id: MacroUserIdStr<'_>,
        request: SendingInboxRequest<'_>,
    ) -> impl Future<Output = Result<ResolvedSendingInbox, EmailErr>> + Send;
}

impl<T: EmailService> SendingInboxResolver for T {
    fn resolve_sending_inbox(
        &self,
        macro_id: MacroUserIdStr<'_>,
        request: SendingInboxRequest<'_>,
    ) -> impl Future<Output = Result<ResolvedSendingInbox, EmailErr>> + Send {
        EmailService::resolve_sending_inbox(self, macro_id, request)
    }
}

/// Use case: send a message carrying files the caller already holds, such
/// as an event's iCalendar file.
pub trait EmailFileSendService: Send + Sync + 'static {
    /// Like [`EmailService::send_message`], with every file staged on the
    /// message before delivery is queued. With no files it is exactly a send.
    fn send_message_with_files(
        &self,
        link: &Link,
        accessible_inboxes: &[Link],
        input: CreateDraftInput,
        files: Vec<SourcedAttachment>,
    ) -> impl Future<Output = Result<CreatedDraft, EmailErr>> + Send;
}

/// Use case: send a message carrying Macro documents as attachments.
///
/// Object-safe (boxed future) so a tool context can hold any implementation
/// behind one `Arc<dyn _>`, and hosts without attachment infrastructure can
/// hold [`NoOpEmailAttachmentSender`] under the same type.
pub trait EmailAttachmentSendService: Send + Sync + 'static {
    /// Like [`EmailService::send_message`], with every document in
    /// `attachments` staged on the message before delivery is queued. With
    /// no attachments it is exactly a send.
    fn send_message_with_attachments<'a>(
        &'a self,
        link: &'a Link,
        accessible_inboxes: &'a [Link],
        input: CreateDraftInput,
        attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Pin<Box<dyn Future<Output = Result<CreatedDraft, EmailErr>> + Send + 'a>>;
}

/// [`EmailAttachmentSendService`] for hosts with no attachment source or
/// storage. Sends without attachments pass through to `service`; a send
/// naming attachments fails with [`EmailErr::AttachmentsUnavailable`]
/// rather than silently dropping them.
pub struct NoOpEmailAttachmentSender<T>(pub Arc<T>);

impl<T: DraftSendService> EmailAttachmentSendService for NoOpEmailAttachmentSender<T> {
    fn send_message_with_attachments<'a>(
        &'a self,
        link: &'a Link,
        accessible_inboxes: &'a [Link],
        input: CreateDraftInput,
        attachments: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Pin<Box<dyn Future<Output = Result<CreatedDraft, EmailErr>> + Send + 'a>> {
        Box::pin(async move {
            if !attachments.is_empty() {
                return Err(EmailErr::AttachmentsUnavailable);
            }
            self.0.send_message(link, accessible_inboxes, input).await
        })
    }
}

/// No-op enqueuer for callers that don't need send capability.
#[derive(Clone)]
pub struct NoOpEnqueuer;

impl EmailMessageEnqueuer for NoOpEnqueuer {
    type Err = std::convert::Infallible;
    const MAX_LABEL_WRITE_MESSAGES: usize = usize::MAX;

    async fn enqueue_scheduled_message(
        &self,
        _link_id: Uuid,
        _message_id: Uuid,
        _delay_seconds: Option<i32>,
    ) -> Result<(), Self::Err> {
        Ok(())
    }

    async fn enqueue_gmail_ops_modify_labels_batch(
        &self,
        _link_id: Uuid,
        _messages: Vec<(Uuid, String)>,
        _labels_to_add: Vec<String>,
        _labels_to_remove: Vec<String>,
        _pending_write_id: Uuid,
    ) -> Result<(), Self::Err> {
        Ok(())
    }

    async fn enqueue_gmail_ops_block_sender(
        &self,
        _link_id: Uuid,
        _email_address: String,
    ) -> Result<(), Self::Err> {
        Ok(())
    }

    async fn enqueue_gmail_ops_unblock_sender(
        &self,
        _link_id: Uuid,
        _email_address: String,
    ) -> Result<(), Self::Err> {
        Ok(())
    }
}

/// No-op [`EmailService`] for binaries that need to satisfy the bound but
/// never call email — e.g. schema-only GraphQL SDL export. Every method
/// errors; swap for a real implementation if you actually need email.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoOpEmailService;

fn no_op_email_err() -> EmailErr {
    EmailErr::RepoErr(anyhow::anyhow!("no-op email service"))
}

impl EmailUserService for NoOpEmailService {
    async fn get_user_email_senders(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _link_id: Uuid,
    ) -> Result<Vec<crate::domain::senders::SendAsAddress>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_user_email_labels(
        &self,
        _macro_id: MacroUserIdStr<'static>,
    ) -> Result<Vec<LinkLabel>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_user_email_links(
        &self,
        _macro_id: MacroUserIdStr<'static>,
    ) -> Result<Vec<UserEmailLink>, EmailErr> {
        Err(no_op_email_err())
    }
}

impl EmailService for NoOpEmailService {
    async fn resolve_thread_read_id(
        &self,
        _macro_id: MacroUserIdStr<'_>,
        thread_id: Uuid,
    ) -> Result<Uuid, EmailErr> {
        Ok(thread_id)
    }

    async fn resolve_message_operation(
        &self,
        _actor: MacroUserIdStr<'static>,
        _request: super::models::mailbox_operation::MessageResolutionRequest,
    ) -> Result<Uuid, EmailErr> {
        Err(no_op_email_err())
    }
    async fn send_message_for_user(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _link_id: Option<Uuid>,
        _input: CreateDraftInput,
    ) -> Result<CreatedDraft, EmailErr> {
        Err(no_op_email_err())
    }

    async fn set_thread_archived(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _thread_id: Uuid,
        _archived: bool,
    ) -> Result<(), EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_email_thread_previews(
        &self,
        _req: GetEmailsRequest,
    ) -> Result<PaginatedCursor<EnrichedEmailThreadPreview, Uuid, SimpleSortMethod, ()>, EmailErr>
    {
        Err(no_op_email_err())
    }

    async fn get_link_by_auth_id_and_macro_id(
        &self,
        _auth_id: &str,
        _macro_id: MacroUserIdStr<'_>,
    ) -> Result<Option<Link>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_inboxes_for_macro_id(
        &self,
        _macro_id: MacroUserIdStr<'_>,
    ) -> Result<Vec<Link>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn resolve_sending_inbox(
        &self,
        _macro_id: MacroUserIdStr<'_>,
        _request: SendingInboxRequest<'_>,
    ) -> Result<ResolvedSendingInbox, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_owned_link_for_thread(
        &self,
        _macro_id: MacroUserIdStr<'_>,
        _thread_id: Uuid,
    ) -> Result<Option<Link>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_thread_with_messages(
        &self,
        _receipt: EntityAccessReceipt<ViewAccessLevel>,
        _offset: i64,
        _limit: i64,
    ) -> Result<Option<Thread>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_thread_parsed(
        &self,
        _receipt: EntityAccessReceipt<ViewAccessLevel>,
        _offset: i64,
        _limit: i64,
    ) -> Result<Option<ParsedThread>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn create_draft(
        &self,
        _link: &Link,
        _accessible_inboxes: &[Link],
        _input: CreateDraftInput,
    ) -> Result<CreatedDraft, EmailErr> {
        Err(no_op_email_err())
    }

    async fn save_draft_for_user(
        &self,
        _macro_id: MacroUserIdStr<'_>,
        _link_id: Option<Uuid>,
        _input: CreateDraftInput,
    ) -> Result<SavedUserDraft, EmailErr> {
        Err(no_op_email_err())
    }

    async fn delete_draft_for_user(
        &self,
        _macro_id: MacroUserIdStr<'_>,
        _draft_id: Uuid,

        _expected_generation: i32,
    ) -> Result<DeletedUserDraft, EmailErr> {
        Err(no_op_email_err())
    }

    async fn send_message(
        &self,
        _link: &Link,
        _accessible_inboxes: &[Link],
        _input: CreateDraftInput,
    ) -> Result<CreatedDraft, EmailErr> {
        Err(no_op_email_err())
    }

    async fn list_labels(&self, _link: &Link) -> Result<Vec<LinkLabel>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn update_thread_labels(
        &self,
        _link: &Link,
        _thread_id: Uuid,
        _label_id: Uuid,
        _add: bool,
    ) -> Result<UpdateThreadLabelsResult, EmailErr> {
        Err(no_op_email_err())
    }

    async fn mark_thread_unread(
        &self,
        _macro_id: MacroUserIdStr<'static>,
        _thread_id: Uuid,
    ) -> Result<(), EmailErr> {
        Err(no_op_email_err())
    }

    async fn update_thread_project(
        &self,
        _thread_receipt: EntityAccessReceipt<EditAccessLevel>,
        _project_receipt: Option<EntityAccessReceipt<EditAccessLevel>>,
    ) -> Result<Option<String>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn upsert_email_filter(
        &self,
        _link: &Link,
        _input: UpsertEmailFilterInput,
    ) -> Result<EmailFilter, EmailErr> {
        Err(no_op_email_err())
    }

    async fn set_sender_policy(
        &self,
        _actor: &MacroUserIdStr<'_>,
        _link: &Link,
        _sender_email: &str,
        _policy: SenderPolicy,
    ) -> Result<(), EmailErr> {
        Err(no_op_email_err())
    }

    async fn delete_email_filter(&self, _link: &Link, _filter_id: Uuid) -> Result<bool, EmailErr> {
        Err(no_op_email_err())
    }

    async fn list_email_filters(&self, _link: &Link) -> Result<Vec<EmailFilter>, EmailErr> {
        Err(no_op_email_err())
    }
}

impl EmailThreadMetadataService for NoOpEmailService {
    async fn get_email_thread_metadata(
        &self,
        _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Result<HashMap<Uuid, EmailThreadMetadata>, EmailErr> {
        Err(no_op_email_err())
    }
}

impl EmailThreadMailProjectionService for NoOpEmailService {
    async fn get_email_thread_mail_projections(
        &self,
        _viewer: MacroUserIdStr<'static>,
        _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Result<HashMap<Uuid, EmailThreadMailProjection>, EmailErr> {
        Err(no_op_email_err())
    }
}

impl EmailThreadPreviewService for NoOpEmailService {
    async fn get_email_thread_previews_by_receipts(
        &self,
        _viewer: MacroUserIdStr<'static>,
        _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Result<Vec<EnrichedEmailThreadPreview>, EmailErr> {
        Err(no_op_email_err())
    }
}

impl EmailContentService for NoOpEmailService {
    async fn get_latest_messages_parsed(
        &self,
        _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Result<HashMap<Uuid, ParsedMessage>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_latest_messages_full(
        &self,
        _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
    ) -> Result<HashMap<Uuid, Message>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_messages_parsed(
        &self,
        _receipt: EntityAccessReceipt<ViewAccessLevel>,
        _offset: i64,
        _limit: i64,
    ) -> Result<Option<Vec<ParsedMessage>>, EmailErr> {
        Err(no_op_email_err())
    }

    async fn get_messages_full(
        &self,
        _receipt: EntityAccessReceipt<ViewAccessLevel>,
        _offset: i64,
        _limit: i64,
    ) -> Result<Option<Vec<Message>>, EmailErr> {
        Err(no_op_email_err())
    }
}

/// Outcome of a first-inbox provisioning attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FirstInboxProvisionOutcome {
    /// The inbox was provisioned and a backfill was started.
    Provisioned,
    /// The service declined the request as a no-op: the inbox is already
    /// initialized or the user holds no Gmail grant. Expected, not an error.
    Skipped,
}

/// Port for provisioning the calling user's primary inbox.
pub trait FirstInboxProvisioner: Send + Sync + 'static {
    /// Provisions the caller's primary inbox. Idempotent, so safe to invoke on
    /// every authentication.
    fn provision_first_inbox(
        &self,
        access_token: &str,
    ) -> impl Future<Output = anyhow::Result<FirstInboxProvisionOutcome>> + Send;
}