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.

109 KB
Raw Blame
//! Call service implementation.

#[cfg(test)]
mod test;

mod channel_startup;
mod guest_chat;
mod meeting_invites;
mod meetings;
mod orphan_rooms;
mod reconcile;

use connection::domain::ports::ConnectionService;
use entity_access::domain::models::{
    EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
    ViewAccessLevel,
};
use entity_access::domain::ports::EntityAccessService;
use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::team_share::{
    AuthorizedTeamShareCommand, TeamShareLevel, TeamShareRequest, authorize_team_share,
};
use notification::domain::models::apple::VoipPushPayload;
use notification::domain::models::apple::{
    APNSPushNotification, Alert, AlertDictionary, Aps, PushNotificationData,
};
use notification::domain::models::{
    NotifCollapseKey, Notification, NotificationExtIos, SendNotificationRequestBuilder,
};
use notification::domain::ports::VoipPushSender;
use notification::domain::service::NotificationIngress;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use subtle::ConstantTimeEq;

use uuid::Uuid;

use crate::domain::events::{
    CallArchiveReason, CallMacroEvent, CallRecordArchivedMetadata, CallRecordDeletedMetadata,
    CallRecordSummarizedMetadata, CallRecordUpdatedMetadata, CallRecordingReadyMetadata,
    CallStartedMetadata,
};
use crate::domain::models::{
    CallRecordPage, EditCallRecordRepoArgs, EditCallRecordRequest, EditCallTranscriptRequest,
    VoipPushPayloadRequest,
};
use crate::domain::notification_events::{
    CallNotificationEvent, CallNotificationMacroEvent, CallNotificationMetadata,
};

use super::meetings::{
    ActiveMeeting, CreateMeetingRequest, GuestJoinRequest, InviteMeetingUsersRequest, Meeting,
    MeetingInvitePermissions, MeetingPreparation, MeetingToken, UpdateMeetingRequest,
};
use super::models::{
    ActiveCallsResponse, AddParticipantError, ArchivedCall, Call, CallActiveResponse, CallError,
    CallPeople, CallRecord, CallRecordTranscriptSegment, CallTokenResponse,
    CallTranscriptCustomSpeakerResult, EgressS3Config, EnrichedCallTranscript,
    GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetCallRecordsRequest,
    JoinCallRequest, LeaveCallResponse, LiveCallKind, LiveCallParticipantsResponse,
    LiveCallSummary, LiveCallsResponse, OnOtherCall, RingStatus, RingStatusResponse,
    TranscriptSegmentRequest,
};
use super::ports::{
    CallRecordQueryService, CallRecordReader, CallRepository, CallRtcClient, CallService,
    CallStartLimiter, CallSummarizer, NoOpVoiceRepository, ProgrammaticCallGate, RecordingDownload,
    RecordingStorage, VoiceRepository,
};

/// The concrete call service implementation.
pub struct CallServiceImpl<
    R: CallRepository,
    C: CallRtcClient,
    Cn: ConnectionService,
    E: EntityAccessService,
    N: NotificationIngress,
    S: RecordingStorage,
    Sm: CallSummarizer = NoopCallSummarizer,
    V: VoipPushSender = (),
    Vr: VoiceRepository = NoOpVoiceRepository,
    B: MacroEventBroker = NoopMacroEventBroker,
> {
    repo: R,
    rtc_client: Arc<C>,
    connection_service: Arc<Cn>,
    entity_access_service: E,
    notification_ingress: Arc<N>,
    recording_storage: S,
    server_url: String,
    egress_s3_config: Option<EgressS3Config>,
    internal_call_secret: Option<String>,
    summarizer: Option<Sm>,
    voip_push_sender: Arc<V>,
    voice_repo: Vr,
    ring_status_base_url: Option<String>,
    event_broker: B,
    channel_threads: Option<Arc<dyn crate::domain::ports::ChannelThreads>>,
    start_limiter: Option<Arc<dyn CallStartLimiter>>,
    programmatic_call_gate: Option<Arc<dyn ProgrammaticCallGate>>,
}

impl<
    R: CallRepository,
    C: CallRtcClient,
    Cn: ConnectionService,
    E: EntityAccessService,
    N: NotificationIngress,
    S: RecordingStorage,
    Sm: CallSummarizer,
> CallServiceImpl<R, C, Cn, E, N, S, Sm, (), NoOpVoiceRepository>
{
    /// Create a new call service.
    pub fn new(
        repo: R,
        rtc_client: C,
        connection_service: Cn,
        entity_access_service: E,
        notification_ingress: N,
        recording_storage: S,
        server_url: impl Into<String>,
    ) -> Self {
        Self {
            repo,
            rtc_client: Arc::new(rtc_client),
            connection_service: Arc::new(connection_service),
            entity_access_service,
            notification_ingress: Arc::new(notification_ingress),
            recording_storage,
            server_url: server_url.into(),
            egress_s3_config: None,
            internal_call_secret: None,
            summarizer: None,
            voip_push_sender: Arc::new(()),
            voice_repo: NoOpVoiceRepository,
            ring_status_base_url: None,
            event_broker: NoopMacroEventBroker,
            channel_threads: None,
            start_limiter: None,
            programmatic_call_gate: None,
        }
    }
}

impl<
    R: CallRepository,
    C: CallRtcClient,
    Cn: ConnectionService,
    E: EntityAccessService,
    N: NotificationIngress,
    S: RecordingStorage,
    Sm: CallSummarizer,
    V: VoipPushSender,
    Vr: VoiceRepository,
    B: MacroEventBroker,
> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>
{
    /// Let new channel calls discuss in a thread in their channel.
    pub fn with_channel_threads(
        mut self,
        channel_threads: Arc<dyn crate::domain::ports::ChannelThreads>,
    ) -> Self {
        self.channel_threads = Some(channel_threads);
        self
    }

    /// Attach a per-account budget for calls that ring others.
    pub fn with_start_limiter(mut self, limiter: impl CallStartLimiter + 'static) -> Self {
        self.start_limiter = Some(Arc::new(limiter));
        self
    }

    /// Attach the per-caller switch for explicit programmatic call routes.
    pub fn with_programmatic_call_gate(mut self, gate: impl ProgrammaticCallGate) -> Self {
        self.programmatic_call_gate = Some(Arc::new(gate));
        self
    }

    /// Enable auto-recording with the given S3 configuration.
    pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {
        self.egress_s3_config = Some(s3_config);
        self
    }

    /// Set the shared secret used to validate internal call requests.
    pub fn with_internal_call_secret(mut self, secret: String) -> Self {
        self.internal_call_secret = Some(secret);
        self
    }

    /// Set the public base URL used to build the per-call ring-status URL
    /// included in VoIP push payloads. When unset, payloads omit the URL and
    /// native clients skip ring-status polling.
    pub fn with_ring_status_base_url(mut self, base_url: String) -> Self {
        self.ring_status_base_url = Some(base_url);
        self
    }

    /// Enable AI call summarization with the given [`CallSummarizer`]
    /// implementation. When unset, calls are never summarized.
    pub fn with_summarizer(mut self, summarizer: Sm) -> Self {
        self.summarizer = Some(summarizer);
        self
    }

    /// Attach a VoIP push sender so incoming-call PushKit notifications are
    /// delivered when a new call is created.
    pub fn with_voip_push_sender<V2: VoipPushSender>(
        self,
        sender: V2,
    ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, V2, Vr, B> {
        CallServiceImpl {
            repo: self.repo,
            rtc_client: self.rtc_client,
            connection_service: self.connection_service,
            entity_access_service: self.entity_access_service,
            notification_ingress: self.notification_ingress,
            recording_storage: self.recording_storage,
            server_url: self.server_url,
            egress_s3_config: self.egress_s3_config,
            internal_call_secret: self.internal_call_secret,
            summarizer: self.summarizer,
            voip_push_sender: Arc::new(sender),
            voice_repo: self.voice_repo,
            ring_status_base_url: self.ring_status_base_url,
            event_broker: self.event_broker,
            channel_threads: self.channel_threads,
            start_limiter: self.start_limiter,
            programmatic_call_gate: self.programmatic_call_gate,
        }
    }

    /// Swap the voice repository.
    pub fn with_voice_repo<Vr2: VoiceRepository>(
        self,
        voice_repo: Vr2,
    ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr2, B> {
        CallServiceImpl {
            repo: self.repo,
            rtc_client: self.rtc_client,
            connection_service: self.connection_service,
            entity_access_service: self.entity_access_service,
            notification_ingress: self.notification_ingress,
            recording_storage: self.recording_storage,
            server_url: self.server_url,
            egress_s3_config: self.egress_s3_config,
            internal_call_secret: self.internal_call_secret,
            summarizer: self.summarizer,
            voip_push_sender: self.voip_push_sender,
            voice_repo,
            ring_status_base_url: self.ring_status_base_url,
            event_broker: self.event_broker,
            channel_threads: self.channel_threads,
            start_limiter: self.start_limiter,
            programmatic_call_gate: self.programmatic_call_gate,
        }
    }

    /// Replace the event broker while preserving every other service dependency.
    pub fn with_event_broker<B2: MacroEventBroker>(
        self,
        event_broker: B2,
    ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B2> {
        CallServiceImpl {
            repo: self.repo,
            rtc_client: self.rtc_client,
            connection_service: self.connection_service,
            entity_access_service: self.entity_access_service,
            notification_ingress: self.notification_ingress,
            recording_storage: self.recording_storage,
            server_url: self.server_url,
            egress_s3_config: self.egress_s3_config,
            internal_call_secret: self.internal_call_secret,
            summarizer: self.summarizer,
            voip_push_sender: self.voip_push_sender,
            voice_repo: self.voice_repo,
            ring_status_base_url: self.ring_status_base_url,
            event_broker,
            channel_threads: self.channel_threads,
            start_limiter: self.start_limiter,
            programmatic_call_gate: self.programmatic_call_gate,
        }
    }

    fn publish_call_event(&self, event: &CallMacroEvent) {
        publish_call_event(&self.event_broker, event);
    }

    fn publish_call_notification(&self, event: CallNotificationEvent) {
        publish_call_notification(&self.event_broker, event);
    }

    /// Authorize an explicit (`teamShareAccessLevel`) or legacy (`shareWithTeam`)
    /// canonical team-share change on an archived call against the persisted
    /// creator.
    ///
    /// Returns `Ok(None)` without loading anything when the request carries
    /// neither input, so renames and link changes never take the shared
    /// team-share guard. Calls only share with the team at View, so any other
    /// explicit level is rejected before facts load. Effective Edit (or even
    /// Owner) access is not enough: only the call's actual creator may share it.
    async fn authorize_call_team_share(
        &self,
        receipt: &EntityAccessReceipt<EditAccessLevel>,
        call_id: &Uuid,
        request: TeamShareRequest,
    ) -> Result<Option<AuthorizedTeamShareCommand>, CallError> {
        if request == TeamShareRequest::default() {
            return Ok(None);
        }
        if let Some(Some(level)) = request.access_level
            && level != AccessLevel::View
        {
            return Err(CallError::InvalidRequest(
                "calls can only be shared with the team at view access".to_string(),
            ));
        }
        let facts = self.repo.get_team_share_facts(call_id).await?;
        Ok(authorize_team_share(
            receipt.acting_user_id(),
            &facts,
            request,
            TeamShareLevel::View,
        )?)
    }

    fn publish_archived_call_event(
        &self,
        archived: &ArchivedCall,
        archive_reason: CallArchiveReason,
    ) {
        let created_by = match MacroUserIdStr::parse_from_str(&archived.created_by) {
            Ok(created_by) => created_by.into_owned(),
            Err(error) => {
                tracing::error!(
                    error = ?error,
                    call_id = %archived.call_id,
                    "failed to parse stored call creator; skipping archived event"
                );
                return;
            }
        };

        let participants = archived
            .participants
            .iter()
            .filter_map(|participant| {
                MacroUserIdStr::parse_from_str(participant)
                    .inspect_err(|error| {
                        tracing::error!(
                            error = ?error,
                            call_id = %archived.call_id,
                            "failed to parse stored call participant; omitting it from the archived event"
                        );
                    })
                    .ok()
                    .map(MacroUserIdStr::into_owned)
            })
            .collect();

        self.publish_call_event(&CallMacroEvent::record_archived(
            CallRecordArchivedMetadata {
                call_id: archived.call_id,
                channel_id: archived.channel_id,
                created_by,
                started_at: archived.started_at,
                ended_at: archived.ended_at,
                duration_ms: Some(archived.duration_ms),
                participant_count: archived.participants.len(),
                participants,
                has_recording: archived.has_recording,
                archive_reason,
                channel_thread: archived.channel_thread,
            },
        ));
        self.publish_call_notification(CallNotificationEvent::Ended(
            CallNotificationMetadata::new(archived.call_id, archived.channel_id),
        ));
        if archived.has_recording {
            self.publish_call_notification(CallNotificationEvent::RecordingReady(
                CallNotificationMetadata::new(archived.call_id, None),
            ));
        }
    }

    /// Send a call event to all channel members (best-effort).
    async fn send_call_event(
        &self,
        channel_id: &Option<Uuid>,
        message_type: &str,
        message: &serde_json::Value,
        triggered_by_user_id: Option<MacroUserIdStr<'_>>,
    ) {
        let Some(channel_id) = channel_id else {
            return;
        };
        let channel_id_str = channel_id.to_string();
        let users = match self
            .entity_access_service
            .get_users_by_entity(&channel_id_str, EntityType::Channel)
            .await
        {
            Ok(users) => users,
            Err(e) => {
                tracing::error!(error=?e, "failed to fetch channel users for call event");
                return;
            }
        };

        let users: Vec<MacroUserIdStr<'_>> = users
            .into_iter()
            .filter_map(|u| {
                if triggered_by_user_id
                    .as_ref()
                    .is_some_and(|t| u.as_ref() == t.as_ref())
                {
                    None
                } else {
                    Some(u)
                }
            })
            .collect();

        let _ = self
            .connection_service
            .send_channel_message(&users, message_type, message.clone())
            .await
            .inspect_err(|e| tracing::error!(error=?e, message_type, "failed to send call event"));
    }

    /// Send an event to the active participants of a call (best-effort).
    ///
    /// Unlike [`Self::send_call_event`], which fans out to every member of
    /// the channel, this targets only users currently in the call — rows in
    /// `call_participants` with `left_at IS NULL`.
    async fn send_call_participant_event(
        &self,
        call_id: &Uuid,
        message_type: &str,
        message: &serde_json::Value,
    ) {
        let participants = match self.repo.get_participants(call_id).await {
            Ok(p) => p,
            Err(e) => {
                tracing::error!(error=?e, "failed to fetch call participants for event");
                return;
            }
        };

        let users: Vec<MacroUserIdStr<'static>> = participants
            .into_iter()
            .filter_map(|p| {
                MacroUserIdStr::parse_from_str(&p.user_id)
                    .map(CowLike::into_owned)
                    .ok()
            })
            .collect();

        let _ = self
            .connection_service
            .send_channel_message(&users, message_type, message.clone())
            .await
            .inspect_err(|e| tracing::error!(error=?e, message_type, "failed to send call participant event"));
    }

    /// Notify a user's own connections that they answered a call (best-effort).
    ///
    /// Unlike [`Self::send_call_event`], this targets only the answering
    /// user, across all their connected clients, so devices still showing
    /// the incoming-call UI can dismiss it when the call is answered
    /// elsewhere (e.g. stop the desktop ring after an iPhone pickup).
    async fn send_call_answered_event(
        &self,
        channel_id: &Option<Uuid>,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) {
        let mut metadata = CallNotificationMetadata::new(*call_id, *channel_id);
        metadata.user_id = Some(user_id.to_string());
        metadata.recipient_user_id = Some(user_id.to_string());
        self.publish_call_notification(CallNotificationEvent::Answered(metadata));
        let _ = self
            .connection_service
            .send_channel_message(
                &[user_id.copied()],
                "call_answered",
                serde_json::json!({
                    "channel_id": channel_id,
                    "call_id": call_id,
                    "user_id": user_id,
                }),
            )
            .await
            .inspect_err(|e| tracing::error!(error=?e, "failed to send call answered event"));
    }

    /// Notify a user's own connections that they declined a call (best-effort).
    ///
    /// Same audience as [`Self::send_call_answered_event`]: only the declining
    /// user's clients, so a decline on one device (e.g. the iPhone lock
    /// screen) stops the ring on the rest without touching other members.
    async fn send_call_declined_event(
        &self,
        channel_id: &Option<Uuid>,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) {
        let mut metadata = CallNotificationMetadata::new(*call_id, *channel_id);
        metadata.user_id = Some(user_id.to_string());
        metadata.recipient_user_id = Some(user_id.to_string());
        self.publish_call_notification(CallNotificationEvent::Declined(metadata));
        let _ = self
            .connection_service
            .send_channel_message(
                &[user_id.copied()],
                "call_declined",
                serde_json::json!({
                    "channel_id": channel_id,
                    "call_id": call_id,
                    "user_id": user_id,
                }),
            )
            .await
            .inspect_err(|e| tracing::error!(error=?e, "failed to send call declined event"));
    }

    /// Persist a user's decline of `call` and fan it out to their devices.
    async fn decline_active_call(
        &self,
        call: &Call,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<(), CallError> {
        self.repo
            .record_decline(&call.id, user_id.copied())
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        self.send_call_declined_event(&call.channel_id, &call.id, user_id)
            .await;
        Ok(())
    }

    /// Resolve the room and identity a VoIP-delivered RTC token authorizes.
    fn verify_ring_token(
        &self,
        bearer_token: &str,
    ) -> Result<(String, MacroUserIdStr<'static>), CallError> {
        let verified = self
            .rtc_client
            .verify_access_token(bearer_token)
            .map_err(|e| {
                tracing::warn!(error=?e, "ring token verification failed");
                CallError::Auth
            })?;
        let room = verified.room.ok_or(CallError::Auth)?;
        let identity = MacroUserIdStr::parse_from_str(&verified.identity)
            .map_err(|_| CallError::Auth)?
            .into_owned();
        Ok((room, identity))
    }
}

/// Decide the per-user ring status from the room's active call (if any),
/// the call id the client is polling for, and whether the user is an
/// active participant of, or has declined, that call.
///
/// A room whose active call differs from the polled one means the polled
/// call is over and a newer call replaced it — the stale ring is dead.
/// Joining outranks an earlier decline: a user who declined on one device
/// and then picked up on another is in the call.
fn resolve_ring_status(
    active_call: Option<&Call>,
    requested_call_id: &Uuid,
    is_participant: bool,
    has_declined: bool,
) -> RingStatus {
    match active_call {
        None => RingStatus::Ended,
        Some(call) if call.id != *requested_call_id => RingStatus::Ended,
        Some(_) if is_participant => RingStatus::Answered,
        Some(_) if has_declined => RingStatus::Declined,
        Some(_) => RingStatus::Ringing,
    }
}

/// Normalize the team-share inputs of an edit on a live call into the pending
/// share-with-team toggle: `Ok(None)` when neither input is present.
///
/// Calls only share at View, so any other explicit level is rejected, as are
/// explicit and legacy inputs that disagree.
fn live_share_intent(request: TeamShareRequest) -> Result<Option<bool>, CallError> {
    let explicit = match request.access_level {
        Some(Some(AccessLevel::View)) => Some(true),
        Some(Some(_)) => {
            return Err(CallError::InvalidRequest(
                "calls can only be shared with the team at view access".to_string(),
            ));
        }
        Some(None) => Some(false),
        None => None,
    };
    match (explicit, request.legacy_enabled) {
        (Some(explicit), Some(legacy)) if explicit != legacy => Err(CallError::InvalidRequest(
            "legacy and explicit team-share inputs contradict each other".to_string(),
        )),
        (Some(explicit), _) => Ok(Some(explicit)),
        (None, legacy) => Ok(legacy),
    }
}

fn event_actor_user_id(auth: &EntityAccessAuth) -> Option<MacroUserIdStr<'static>> {
    match auth {
        EntityAccessAuth::Authenticated(user_id) => Some(user_id.clone().into_owned()),
        EntityAccessAuth::Bot(_)
        | EntityAccessAuth::Unauthenticated
        | EntityAccessAuth::Internal => None,
    }
}

fn exclude_voip_recipients<'a>(
    recipient_ids: HashSet<MacroUserIdStr<'a>>,
    voip_recipient_ids: &HashSet<MacroUserIdStr<'static>>,
) -> HashSet<MacroUserIdStr<'a>> {
    recipient_ids
        .into_iter()
        .filter(|recipient_id| {
            !voip_recipient_ids
                .iter()
                .any(|voip_recipient_id| voip_recipient_id.as_ref() == recipient_id.as_ref())
        })
        .collect()
}

/// Group call recipients by the channel name each of them sees.
///
/// A DM is named after the *other* participant, so resolving the channel
/// name from the caller's perspective would label the incoming call with the
/// callee's own name. Every recipient is pushed the name they know the
/// channel by; recipients whose name could not be resolved share a `None`
/// group. Named channels collapse into a single group.
fn group_recipients_by_channel_name<'a>(
    recipient_ids: impl IntoIterator<Item = MacroUserIdStr<'a>>,
    channel_names_by_recipient: &HashMap<MacroUserIdStr<'static>, String>,
) -> HashMap<Option<String>, HashSet<MacroUserIdStr<'a>>> {
    let mut groups: HashMap<Option<String>, HashSet<MacroUserIdStr<'a>>> = HashMap::new();
    for recipient_id in recipient_ids {
        let channel_name = channel_names_by_recipient
            .iter()
            .find(|(viewer, _)| viewer.as_ref() == recipient_id.as_ref())
            .map(|(_, name)| name.clone());
        groups.entry(channel_name).or_default().insert(recipient_id);
    }
    groups
}

/// Producer-side payload for the "call started" notification.
///
/// Shares its wire shape and [`Notification::TYPE_NAME`] (`call_started`) with
/// the read-side `model_notifications::CallStartedMetadata`, which
/// `NotifEvent` uses to render the notification feed. Keep the two in sync.
#[derive(Serialize, Deserialize, Clone)]
struct CallStartedNotification {
    sender_profile_picture_url: Option<String>,
    channel_name: Option<String>,
}

impl Notification for CallStartedNotification {
    const TYPE_NAME: &'static str = "call_started";
}

impl NotificationExtIos for CallStartedNotification {
    type NotifData = PushNotificationData;

    fn collapse_key(&self, entity: &model_entity::Entity<'_>) -> NotifCollapseKey {
        NotifCollapseKey::new(Self::TYPE_NAME).append(&entity.entity_id)
    }

    fn as_apns<'a>(
        &self,
        sender_id: Option<MacroUserIdStr<'a>>,
        _entity: &model_entity::Entity<'_>,
        notification_id: uuid::Uuid,
    ) -> Option<APNSPushNotification<Self::NotifData>> {
        Some(APNSPushNotification {
            aps: Aps {
                alert: Some(Alert::Dictionary(AlertDictionary {
                    title: Some(match &self.channel_name {
                        Some(name) => format!("Incoming Call in #{name}"),
                        None => "Incoming Call".to_string(),
                    }),
                    body: Some(format!(
                        "{} is calling you",
                        sender_id
                            .as_ref()
                            .map(|e| e.email_str())
                            .unwrap_or("Someone")
                    )),
                    ..Default::default()
                })),
                ..Default::default()
            },
            push_notification_data: PushNotificationData {
                notification_id,
                sender_profile_picture_url: self.sender_profile_picture_url.clone(),
                recipient_id: None,
                navigation: None,
            },
        })
    }
}

impl<
    R: CallRepository + Clone,
    C: CallRtcClient,
    Cn: ConnectionService,
    E: EntityAccessService,
    N: NotificationIngress,
    S: RecordingStorage,
    Sm: CallSummarizer + Clone,
    V: VoipPushSender,
    Vr: VoiceRepository + Clone,
    B: MacroEventBroker + Clone,
> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>
{
    async fn programmatic_calls_enabled(&self, caller: MacroUserIdStr<'_>) -> bool {
        match &self.programmatic_call_gate {
            Some(gate) => gate.enabled_for(caller).await,
            None => false,
        }
    }

    async fn prepare_meeting(
        &self,
        actor: MacroUserIdStr<'_>,
    ) -> Result<MeetingPreparation, CallError> {
        self.prepare_invitation_room(actor).await
    }
    async fn cancel_meeting_preparation(
        &self,
        actor: MacroUserIdStr<'_>,
        id: Uuid,
    ) -> Result<(), CallError> {
        self.cancel_invitation_room(actor, id).await
    }
    async fn create_meeting(
        &self,
        actor: MacroUserIdStr<'_>,
        request: CreateMeetingRequest,
    ) -> Result<Meeting, CallError> {
        self.create_invitation(actor, request).await
    }
    async fn list_meetings(&self, actor: MacroUserIdStr<'_>) -> Result<Vec<Meeting>, CallError> {
        self.repo.list_meetings(actor.as_ref()).await
    }
    async fn list_active_meetings(
        &self,
        actor: MacroUserIdStr<'_>,
    ) -> Result<Vec<ActiveMeeting>, CallError> {
        self.repo
            .list_active_meetings(actor.as_ref())
            .await
            .map(|meetings| meetings.into_iter().map(ActiveMeeting::from).collect())
    }
    async fn invite_to_meeting(
        &self,
        actor: MacroUserIdStr<'_>,
        token: MeetingToken,
        email: String,
    ) -> Result<(), CallError> {
        self.email_invitation(actor, token, email).await
    }
    async fn get_meeting_invite_permissions(
        &self,
        actor: MacroUserIdStr<'_>,
        token: MeetingToken,
    ) -> Result<MeetingInvitePermissions, CallError> {
        self.meeting_invite_permissions(actor, token).await
    }
    async fn invite_users_to_meeting(
        &self,
        actor: MacroUserIdStr<'_>,
        token: MeetingToken,
        request: InviteMeetingUsersRequest,
    ) -> Result<(), CallError> {
        self.ring_meeting_invitation(actor, token, request).await
    }
    async fn update_meeting(
        &self,
        actor: MacroUserIdStr<'_>,
        meeting_id: &Uuid,
        request: UpdateMeetingRequest,
    ) -> Result<Meeting, CallError> {
        self.repo
            .update_meeting(meeting_id, actor.as_ref(), request.validate()?)
            .await?
            .ok_or_else(|| CallError::Forbidden("Only the meeting owner can update it".to_string()))
    }
    async fn cancel_meeting(
        &self,
        actor: MacroUserIdStr<'_>,
        meeting_id: &Uuid,
    ) -> Result<(), CallError> {
        if self.repo.cancel_meeting(meeting_id, actor.as_ref()).await? {
            Ok(())
        } else {
            Err(CallError::Forbidden(
                "Only the meeting owner can cancel it".to_string(),
            ))
        }
    }
    async fn share_call(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<Meeting, CallError> {
        self.share_invitation(receipt).await
    }
    async fn get_meeting(&self, token: MeetingToken) -> Result<Meeting, CallError> {
        self.resolve_invitation(&token).await
    }
    async fn get_meeting_participants(
        &self,
        token: MeetingToken,
        actor: Option<MacroUserIdStr<'_>>,
    ) -> Result<super::meetings::MeetingParticipants, CallError> {
        self.preview_invitation(token, actor).await
    }
    async fn join_meeting(
        &self,
        token: MeetingToken,
        actor: MacroUserIdStr<'_>,
    ) -> Result<CallTokenResponse, CallError> {
        self.join_invitation(
            token,
            actor,
            JoinCallRequest {
                on_other_call: OnOtherCall::Switch,
                replace: true,
                ..Default::default()
            },
            false,
            false,
        )
        .await
    }
    async fn join_meeting_with_options(
        &self,
        token: MeetingToken,
        actor: MacroUserIdStr<'_>,
        request: JoinCallRequest,
        credential_is_program: bool,
        agent_attributed: bool,
    ) -> Result<CallTokenResponse, CallError> {
        self.join_invitation(
            token,
            actor,
            request,
            credential_is_program,
            agent_attributed,
        )
        .await
    }
    async fn join_meeting_guest(
        &self,
        token: MeetingToken,
        request: GuestJoinRequest,
    ) -> Result<CallTokenResponse, CallError> {
        self.join_guest_invitation(token, request).await
    }
    async fn leave_meeting(
        &self,
        token: MeetingToken,
        bearer: &str,
    ) -> Result<LeaveCallResponse, CallError> {
        self.leave_invitation(token, bearer).await
    }

    fn validate_internal_call(&self, token: &str) -> bool {
        self.internal_call_secret
            .as_deref()
            .is_some_and(|secret| secret.as_bytes().ct_eq(token.as_bytes()).into())
    }

    #[tracing::instrument(err, skip(self))]
    async fn check_active_call(
        &self,
        channel_id: &Uuid,
    ) -> Result<Option<CallActiveResponse>, CallError> {
        let call = self
            .repo
            .get_active_call_by_channel(channel_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;

        Ok(call.and_then(|c| {
            Some(CallActiveResponse {
                call_id: c.id,
                channel_id: c.channel_id?,
                created_by: c.created_by,
                created_at: c.created_at,
            })
        }))
    }

    #[tracing::instrument(err, skip(self))]
    async fn reconcile_stale_calls(&self) -> Result<(), CallError> {
        let now = chrono::Utc::now();
        let calls = self
            .repo
            .list_active_calls()
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        for call in &calls {
            self.reconcile_call(call, now)
                .await
                .inspect_err(|error| {
                    tracing::warn!(call_id = %call.id, error = ?error, "failed to reconcile call")
                })
                .ok();
        }
        // A failed sweep is recorded on its span and retried next interval.
        self.sweep_orphan_rooms(&calls, now).await.ok();
        Ok(())
    }

    #[tracing::instrument(err, skip(self))]
    async fn get_active_calls(
        &self,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<ActiveCallsResponse, CallError> {
        let calls = self
            .repo
            .get_active_calls_for_user(user_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;

        Ok(ActiveCallsResponse { calls })
    }

    #[tracing::instrument(err, skip(self))]
    async fn get_or_create_call(
        &self,
        channel_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<CallTokenResponse, CallError> {
        let (call, started) = match self
            .repo
            .get_call_by_channel_id(channel_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
        {
            Some(existing) => (existing, false),
            None => {
                let call_id = Uuid::now_v7();
                // Room grants must expire with this session, even in a channel.
                let room_name = call_id.to_string();

                // Create RTC room (idempotent in LiveKit).
                self.rtc_client
                    .create_room(&room_name)
                    .await
                    .map_err(CallError::Internal)?;

                // Decided before the row exists, so nobody can read this call
                // and see a discussion it will not keep.
                let channel_thread = match &self.channel_threads {
                    Some(channel_threads) => channel_threads.enabled_for(user_id.copied()).await,
                    None => false,
                };

                // Try to create call record; if another request won the race
                // the ON CONFLICT returns None — re-read the existing call.
                match self
                    .repo
                    .create_call(
                        &call_id,
                        channel_id,
                        &room_name,
                        user_id.copied(),
                        channel_thread,
                    )
                    .await?
                {
                    Some(call) => {
                        // Never blocks the call: the first reply retries it.
                        if channel_thread && let Some(channel_threads) = &self.channel_threads {
                            channel_threads
                                .ensure_root(call.id)
                                .await
                                .inspect_err(|error| {
                                    tracing::error!(
                                        error = ?error,
                                        call_id = %call.id,
                                        "failed to create the call's thread root"
                                    );
                                })
                                .ok();
                        }

                        match MacroUserIdStr::parse_from_str(&call.created_by) {
                            Ok(created_by) => {
                                self.publish_call_event(&CallMacroEvent::started(
                                    CallStartedMetadata {
                                        call_id: call.id,
                                        channel_id: call.channel_id,
                                        created_by: created_by.into_owned(),
                                        created_at: call.created_at,
                                        recording_enabled: self.egress_s3_config.is_some(),
                                    },
                                ));
                                let mut metadata =
                                    CallNotificationMetadata::new(call.id, call.channel_id);
                                metadata.created_by = Some(call.created_by.clone());
                                self.publish_call_notification(CallNotificationEvent::Started(
                                    metadata,
                                ));
                            }
                            Err(error) => {
                                tracing::error!(
                                    error = ?error,
                                    call_id = %call.id,
                                    "failed to parse stored call creator; skipping started event"
                                );
                            }
                        }

                        // Only the allocation winner starts media and ringing. Schedule
                        // before subsequent join steps, so a failed first join cannot
                        // strand the room without recording or notifications.
                        channel_startup::ChannelCallStartup {
                            repo: self.repo.clone(),
                            rtc_client: self.rtc_client.clone(),
                            connection_service: self.connection_service.clone(),
                            entity_access_service: self.entity_access_service.clone(),
                            notification_ingress: self.notification_ingress.clone(),
                            voip_push_sender: self.voip_push_sender.clone(),
                            server_url: self.server_url.clone(),
                            ring_status_base_url: self.ring_status_base_url.clone(),
                            egress_s3_config: self.egress_s3_config.clone(),
                            event_broker: self.event_broker.clone(),
                        }
                        .spawn(
                            call.clone(),
                            *channel_id,
                            user_id.clone().into_owned(),
                        );

                        (call, true)
                    }
                    None => {
                        // A concurrent request owns the active session. Our empty
                        // candidate room carries no participants or recording.
                        self.rtc_client.delete_room(&room_name).await
                            .inspect_err(|error| tracing::error!(error=?error, "failed to remove unused channel call room")).ok();
                        // Another request created the call — read the existing one.
                        (
                            self.repo
                                .get_call_by_channel_id(channel_id)
                                .await
                                .map_err(|e| CallError::Internal(e.into()))?
                                .ok_or_else(|| CallError::NotFound(channel_id.to_string()))?,
                            false,
                        )
                    }
                }
            }
        };

        // A user is active in one call at a time; joining this one switches
        // them out of any other.
        self.leave_other_active_call(user_id.copied(), call.id)
            .await?;

        // Idempotent upsert — handles concurrent joins and rejoin after leave.
        // The DB-level partial unique index is the race-safe backstop: if a
        // concurrent join slipped past the switch above, the adapter
        // returns AddParticipantError::UserAlreadyActive, which we translate
        // to a typed CallError::AlreadyInCall.
        match self.repo.add_participant(&call.id, user_id.copied()).await {
            Ok(_) => {}
            Err(AddParticipantError::UserAlreadyActive) => {
                let channel = self
                    .repo
                    .find_active_call_for_user(user_id.copied())
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?
                    .map(|(id, ch)| ch.unwrap_or(id).to_string())
                    .unwrap_or_else(|| "unknown".to_string());
                return Err(CallError::AlreadyInCall(channel));
            }
            Err(AddParticipantError::Repository(e)) => {
                return Err(CallError::Internal(e));
            }
        }

        // A person may rejoin a row a program of theirs marked. Reset it, or the
        // program-only rule could end the call while they're in it.
        self.repo
            .set_participant_client(&call.id, user_id.as_ref(), "person")
            .await
            .map_err(|e| CallError::Internal(e.into()))?;

        // Tell the user's other devices the call was answered here so they
        // can stop showing the incoming-call UI (best-effort).
        self.send_call_answered_event(&Some(*channel_id), &call.id, user_id.copied())
            .await;

        // Always generate a fresh token (supports reconnection from different devices).
        let token = self
            .rtc_client
            .generate_token(&call.room_name, user_id.copied())
            .await
            .map_err(CallError::Internal)?;

        Ok(CallTokenResponse {
            started,
            call_id: call.id,
            channel_id: Some(*channel_id),
            participant_id: user_id.to_string(),
            share_token: None,
            token,
            room_name: call.room_name,
            server_url: self.server_url.clone(),
        })
    }

    #[tracing::instrument(name = "call.start", err, skip(self, user_id, request), fields(call.id, principal.kind, call.client, outcome))]
    async fn start_call(
        &self,
        channel_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
        request: JoinCallRequest,
        credential_is_program: bool,
    ) -> Result<CallTokenResponse, CallError> {
        tracing::Span::current().record(
            "call.client",
            if credential_is_program {
                "api_key"
            } else {
                "person"
            },
        );
        tracing::Span::current().record(
            "principal.kind",
            if credential_is_program {
                "program"
            } else {
                "user"
            },
        );
        if let Some(call) = self
            .repo
            .get_call_by_channel_id(channel_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
        {
            let result = self
                .join_call(&call.id, user_id, request, credential_is_program)
                .await;
            tracing::Span::current().record("call.id", call.id.to_string());
            tracing::Span::current()
                .record("outcome", if result.is_ok() { "joined" } else { "failed" });
            return result;
        }
        if matches!(request.on_other_call, OnOtherCall::Fail)
            && self
                .repo
                .find_active_call_for_user(user_id.copied())
                .await
                .map_err(|e| CallError::Internal(e.into()))?
                .is_some()
        {
            tracing::Span::current().record("outcome", "in_other_call");
            return Err(CallError::InOtherCall);
        }
        if let Some(limiter) = &self.start_limiter {
            limiter.check(user_id.as_ref()).await?;
        }
        let mut response = self
            .get_or_create_call(channel_id, user_id.copied())
            .await
            .map_err(|error| match error {
                CallError::AlreadyInCall(_) => CallError::InOtherCall,
                other => other,
            })?;
        let agent = self
            .repo
            .is_agent_account(user_id.as_ref())
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        if credential_is_program || agent {
            let program = if agent { "agent" } else { "api_key" };
            self.repo
                .set_participant_client(&response.call_id, user_id.as_ref(), program)
                .await
                .map_err(|e| CallError::Internal(e.into()))?;
            response.token = self
                .rtc_client
                .generate_program_token(&response.room_name, user_id, program, request.name.clone())
                .await
                .map_err(CallError::Internal)?;
        } else if let Some(name) = request.name.as_deref() {
            response.token = self
                .rtc_client
                .generate_named_token(&response.room_name, user_id, name)
                .await
                .map_err(CallError::Internal)?;
        }
        tracing::Span::current().record("call.id", response.call_id.to_string());
        tracing::Span::current().record(
            "call.client",
            if agent {
                "agent"
            } else if credential_is_program {
                "api_key"
            } else {
                "person"
            },
        );
        tracing::Span::current().record("outcome", "joined");
        Ok(response)
    }

    #[tracing::instrument(name = "call.join", err, skip(self, user_id, request), fields(call.id = %call_id, principal.kind, call.client, outcome))]
    async fn join_call(
        &self,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
        request: JoinCallRequest,
        credential_is_program: bool,
    ) -> Result<CallTokenResponse, CallError> {
        tracing::Span::current().record(
            "call.client",
            if credential_is_program {
                "api_key"
            } else {
                "person"
            },
        );
        tracing::Span::current().record(
            "principal.kind",
            if credential_is_program {
                "program"
            } else {
                "user"
            },
        );
        let call = self
            .repo
            .get_call_by_id(call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .ok_or_else(|| {
                tracing::Span::current().record("outcome", "ended");
                CallError::Ended
            })?;
        if !self
            .repo
            .can_join_call(call_id, user_id.as_ref())
            .await
            .map_err(|e| CallError::Internal(e.into()))?
        {
            return Err(CallError::Forbidden(
                "not a call participant or invitee".to_string(),
            ));
        }
        if let Some((other_id, _)) = self
            .repo
            .find_active_call_for_user(user_id.copied())
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            && other_id != *call_id
        {
            if matches!(request.on_other_call, OnOtherCall::Fail) {
                tracing::Span::current().record("outcome", "in_other_call");
                return Err(CallError::InOtherCall);
            }
            self.leave_other_active_call(user_id.copied(), *call_id)
                .await?;
        }
        let connected = self
            .rtc_client
            .list_participant_identities(&call.room_name)
            .await
            .map_err(CallError::Internal)?
            .unwrap_or_default();
        if !request.replace
            && connected
                .iter()
                .any(|identity| identity == user_id.as_ref())
        {
            tracing::Span::current().record("outcome", "already_connected");
            return Err(CallError::AlreadyConnected);
        }
        let add = if call.channel_id.is_some() {
            self.repo.add_participant(call_id, user_id.copied()).await
        } else {
            self.repo
                .add_meeting_participant(call_id, user_id.copied())
                .await
        };
        match add {
            Ok(_) => {}
            Err(AddParticipantError::UserAlreadyActive) => return Err(CallError::InOtherCall),
            Err(AddParticipantError::Repository(error)) => return Err(CallError::Internal(error)),
        }
        let agent = self
            .repo
            .is_agent_account(user_id.as_ref())
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        let client = if agent {
            "agent"
        } else if credential_is_program {
            "api_key"
        } else {
            "person"
        };
        self.repo
            .set_participant_client(call_id, user_id.as_ref(), client)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        let token = if agent || credential_is_program {
            let program = if agent { "agent" } else { "api_key" };
            self.rtc_client
                .generate_program_token(
                    &call.room_name,
                    user_id.copied(),
                    program,
                    request.name.clone(),
                )
                .await
        } else if let Some(name) = request.name.as_deref() {
            self.rtc_client
                .generate_named_token(&call.room_name, user_id.copied(), name)
                .await
        } else {
            self.rtc_client
                .generate_token(&call.room_name, user_id.copied())
                .await
        }
        .map_err(CallError::Internal)?;
        tracing::Span::current().record(
            "call.client",
            if agent {
                "agent"
            } else if credential_is_program {
                "api_key"
            } else {
                "person"
            },
        );
        tracing::Span::current().record("outcome", "joined");
        let share_token = self
            .repo
            .get_meeting_for_call(call_id, false)
            .await?
            .map(|meeting| meeting.share_token.into());
        self.send_call_answered_event(&call.channel_id, call_id, user_id.copied())
            .await;
        Ok(CallTokenResponse {
            started: false,
            call_id: *call_id,
            channel_id: call.channel_id,
            participant_id: user_id.to_string(),
            share_token,
            token,
            room_name: call.room_name,
            server_url: self.server_url.clone(),
        })
    }

    #[tracing::instrument(err, skip(self, user_id))]
    async fn leave_call(
        &self,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<LeaveCallResponse, CallError> {
        let call = self
            .repo
            .get_call_by_id(call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;
        self.repo
            .remove_participant(call_id, user_id.copied())
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        if self.finish_empty_call(&call).await? {
            return Ok(LeaveCallResponse { call_ended: true });
        }
        self.rtc_client
            .remove_participant(&call.room_name, user_id)
            .await
            .map_err(CallError::Internal)?;
        Ok(LeaveCallResponse { call_ended: false })
    }

    async fn get_call_ring_state(
        &self,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<RingStatusResponse, CallError> {
        let call = self
            .repo
            .get_call_by_id(call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        let (is_participant, has_declined) = if call.is_some() {
            let joined = self
                .repo
                .is_participant(call_id, user_id.as_ref())
                .await
                .map_err(|e| CallError::Internal(e.into()))?;
            let declined = self
                .repo
                .has_declined(call_id, user_id.as_ref())
                .await
                .map_err(|e| CallError::Internal(e.into()))?;
            (joined, declined)
        } else {
            (false, false)
        };
        Ok(RingStatusResponse {
            status: resolve_ring_status(call.as_ref(), call_id, is_participant, has_declined),
        })
    }

    #[tracing::instrument(err, skip(self, user_id))]
    async fn get_live_calls(
        &self,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<LiveCallsResponse, CallError> {
        let calls = self
            .repo
            .list_joinable_calls(user_id.as_ref())
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        let mut summaries = Vec::with_capacity(calls.len());
        for call in calls {
            let meeting = self.repo.get_meeting_for_call(&call.id, false).await?;
            let participant_count = self
                .repo
                .get_participant_count(&call.id)
                .await
                .map_err(|e| CallError::Internal(e.into()))?;
            let joined = self
                .repo
                .is_participant(&call.id, user_id.as_ref())
                .await
                .map_err(|e| CallError::Internal(e.into()))?;
            let declined = self
                .repo
                .has_declined(&call.id, user_id.as_ref())
                .await
                .map_err(|e| CallError::Internal(e.into()))?;
            let ringing = matches!(
                resolve_ring_status(Some(&call), &call.id, joined, declined),
                RingStatus::Ringing
            );
            summaries.push(LiveCallSummary {
                call_id: call.id,
                kind: if call.channel_id.is_some() {
                    LiveCallKind::Channel
                } else {
                    LiveCallKind::Standalone
                },
                channel_id: call.channel_id,
                meeting_id: meeting.as_ref().map(|meeting| meeting.id),
                share_token: meeting
                    .as_ref()
                    .map(|meeting| meeting.share_token.as_str().to_string()),
                title: meeting.map(|meeting| meeting.title),
                created_by: call.created_by,
                created_at: call.created_at,
                participant_count,
                ringing,
            });
        }
        Ok(LiveCallsResponse { calls: summaries })
    }

    #[tracing::instrument(err, skip(self, user_id), fields(call.id = %call_id))]
    async fn get_call_participants(
        &self,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<LiveCallParticipantsResponse, CallError> {
        let call = self
            .repo
            .get_call_by_id(call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;
        if !self
            .repo
            .can_join_call(call_id, user_id.as_ref())
            .await
            .map_err(|e| CallError::Internal(e.into()))?
        {
            return Err(CallError::Forbidden(
                "not a call participant or invitee".to_string(),
            ));
        }
        let mut participants = self
            .rtc_client
            .list_live_participants(&call.room_name)
            .await
            .map_err(CallError::Internal)?
            .unwrap_or_default();
        for participant in &mut participants {
            if let Some(identity) = &participant.user_id {
                let user = MacroUserIdStr::parse_from_str(identity)
                    .map_err(|e| CallError::Internal(e.into()))?;
                participant.display_name = self
                    .repo
                    .get_user_display_name(user)
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?
                    .unwrap_or_else(|| "Macro user".to_string());
            }
        }
        Ok(LiveCallParticipantsResponse { participants })
    }

    #[tracing::instrument(err, skip(self))]
    async fn leave_or_end_call(
        &self,
        channel_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<LeaveCallResponse, CallError> {
        let Some(call) = self
            .repo
            .get_call_by_channel_id(channel_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
        else {
            // A stale token may still hold the user in the last call's room.
            self.leave_archived_channel_room(channel_id, user_id).await;
            return Err(CallError::NotFound(channel_id.to_string()));
        };

        // Remove participant from DB (idempotent — no-op if already removed by webhook).
        self.repo
            .remove_participant(&call.id, user_id.copied())
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        let mut metadata = CallNotificationMetadata::new(call.id, call.channel_id);
        metadata.identity = Some(user_id.to_string());
        metadata.user_id = Some(user_id.to_string());
        self.publish_call_notification(CallNotificationEvent::ParticipantLeft(metadata));

        // Kick from LiveKit. The resulting participant_left webhook
        // handles archival and room deletion.
        self.rtc_client
            .remove_participant(&call.room_name, user_id)
            .await
            .inspect_err(
                |e| tracing::error!(error=?e, "failed to remove participant from RTC room"),
            )
            .ok();

        let remaining = self.repo.get_participant_count(&call.id).await.unwrap_or(0);

        Ok(LeaveCallResponse {
            call_ended: remaining == 0,
        })
    }

    #[tracing::instrument(err, skip(self))]
    async fn decline_call(
        &self,
        call_id: &Uuid,
        user_id: MacroUserIdStr<'_>,
    ) -> Result<(), CallError> {
        let call = self
            .repo
            .get_call_by_id(call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;

        self.decline_active_call(&call, user_id).await
    }

    #[tracing::instrument(err, skip(self, bearer_token))]
    async fn decline_ring(&self, call_id: &Uuid, bearer_token: &str) -> Result<(), CallError> {
        let (room, identity) = self.verify_ring_token(bearer_token)?;

        let call = self
            .repo
            .get_call_by_room_name(&room)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .filter(|call| call.id == *call_id)
            .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;

        self.decline_active_call(&call, identity).await
    }

    #[tracing::instrument(err, skip(self, bearer_token))]
    async fn get_ring_status(
        &self,
        call_id: &Uuid,
        bearer_token: &str,
    ) -> Result<RingStatusResponse, CallError> {
        let (room, identity) = self.verify_ring_token(bearer_token)?;

        let active_call = self
            .repo
            .get_call_by_room_name(&room)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;

        // Only consult participation and declines when the room's active call
        // is the one being polled — otherwise the answer is Ended regardless.
        let (is_participant, has_declined) = match &active_call {
            Some(call) if call.id == *call_id => {
                let is_participant = self
                    .repo
                    .is_participant(&call.id, identity.as_ref())
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?;
                let has_declined = self
                    .repo
                    .has_declined(&call.id, identity.as_ref())
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?;
                (is_participant, has_declined)
            }
            _ => (false, false),
        };

        Ok(RingStatusResponse {
            status: resolve_ring_status(
                active_call.as_ref(),
                call_id,
                is_participant,
                has_declined,
            ),
        })
    }

    #[tracing::instrument(err, skip(self, body, auth_token))]
    async fn process_webhook_event(&self, body: &str, auth_token: &str) -> Result<(), CallError> {
        let event = self.rtc_client.receive_webhook(body, auth_token)?;
        if matches!(event.event.as_str(), "egress_started" | "egress_ended") {
            self.link_meeting_recording_webhook(
                event.room_name.as_deref(),
                event.egress_id.as_deref(),
            )
            .await?;
        }

        // Log the participant kind without exposing its identity.
        let participant_kind = match (
            &event.participant_identity,
            &event.guest_identity,
            &event.bot_identity,
        ) {
            (Some(_), _, _) => "user",
            (None, Some(_), _) => "guest",
            (None, None, Some(_)) => "bot",
            (None, None, None) => "none",
        };
        tracing::info!(
            event_type = %event.event,
            event_id = %event.id,
            room_name = ?event.room_name,
            participant_kind,
            "processing call webhook event"
        );

        match event.event.as_str() {
            "room_started" => {
                tracing::info!(room_name = ?event.room_name, "room started");
            }
            "room_finished" => {
                // Safety net: archive if not already handled by participant_left.
                if let Some(room_name) = &event.room_name
                    && let Some(call) = self
                        .repo
                        .get_call_by_room_name(room_name)
                        .await
                        .map_err(|e| CallError::Internal(e.into()))?
                {
                    tracing::info!(call_id = %call.id, room_name, "archiving call on room_finished");
                    let archived = self.repo.archive_call(&call.id).await?;
                    self.publish_archived_call_event(&archived, CallArchiveReason::RoomFinished);

                    // Fire-and-forget summarization now that the
                    // `call_records` row is persisted.
                    self.spawn_summarize_call(archived.call_id);
                    self.spawn_process_voices_for_call(archived.call_id);

                    self.send_call_event(
                        &archived.channel_id,
                        "call_ended",
                        &serde_json::json!({
                            "channel_id": archived.channel_id,
                            "call_id": archived.call_id,
                        }),
                        None,
                    )
                    .await;
                }
            }
            "participant_joined" => {
                if let (Some(room), Some(identity)) = (&event.room_name, event.bot_identity) {
                    if self
                        .repo
                        .get_call_by_room_name(room)
                        .await
                        .map_err(|error| CallError::Internal(error.into()))?
                        .is_none()
                    {
                        self.evict_from_untracked_room(
                            room,
                            orphan_rooms::RoomParticipant::Bot(identity),
                        )
                        .await?;
                    }
                    return Ok(());
                }
                if let (Some(room), Some(identity)) = (&event.room_name, &event.guest_identity) {
                    match self
                        .repo
                        .get_call_by_room_name(room)
                        .await
                        .map_err(|e| CallError::Internal(e.into()))?
                    {
                        Some(call) => {
                            self.repo.reconcile_guest(&call.id, *identity, true).await?;
                            let mut metadata =
                                CallNotificationMetadata::new(call.id, call.channel_id);
                            metadata.identity = Some(identity.to_string());
                            self.publish_call_notification(
                                CallNotificationEvent::ParticipantJoined(metadata),
                            );
                        }
                        None => {
                            self.evict_from_untracked_room(
                                room,
                                orphan_rooms::RoomParticipant::Guest(*identity),
                            )
                            .await?;
                        }
                    }
                    return Ok(());
                }

                let (Some(room_name), Some(participant_identity)) =
                    (&event.room_name, &event.participant_identity)
                else {
                    tracing::warn!(
                        "participant_joined webhook missing room_name or participant_identity"
                    );
                    return Ok(());
                };

                let Some(call) = self
                    .repo
                    .get_call_by_room_name(room_name)
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?
                else {
                    return self
                        .evict_from_untracked_room(
                            room_name,
                            orphan_rooms::RoomParticipant::User(participant_identity.copied()),
                        )
                        .await;
                };

                // Reconcile: idempotent upsert (handles reconnect/race conditions).
                // UserAlreadyActive means our DB has the user active in
                // another call while LiveKit says they joined this one —
                // state drift. Don't fail the whole webhook; log and move on.
                match self
                    .repo
                    .add_participant(&call.id, participant_identity.copied())
                    .await
                {
                    Ok(_) => {
                        tracing::info!(
                            call_id = %call.id,
                            participant = participant_identity.as_ref(),
                            "reconciled participant_joined via webhook"
                        );
                        // Native answers (e.g. iPhone CallKit pickup) connect
                        // straight to LiveKit without hitting the join API, so
                        // this webhook is where the user's other devices learn
                        // the ring was answered (best-effort).
                        self.send_call_answered_event(
                            &call.channel_id,
                            &call.id,
                            participant_identity.copied(),
                        )
                        .await;
                        let mut metadata = CallNotificationMetadata::new(call.id, call.channel_id);
                        metadata.identity = Some(participant_identity.to_string());
                        metadata.user_id = Some(participant_identity.to_string());
                        self.publish_call_notification(CallNotificationEvent::ParticipantJoined(
                            metadata,
                        ));
                    }
                    Err(AddParticipantError::UserAlreadyActive) => {
                        tracing::warn!(
                            call_id = %call.id,
                            participant = participant_identity.as_ref(),
                            "participant_joined webhook: user already active in another call; ignoring reconcile"
                        );
                    }
                    Err(AddParticipantError::Repository(e)) => {
                        return Err(CallError::Internal(e));
                    }
                }
            }
            "participant_left" => {
                if event.bot_identity.is_some() {
                    return Ok(());
                }
                let Some(room_name) = &event.room_name else {
                    return Ok(());
                };
                if event.participant_identity.is_none() && event.guest_identity.is_none() {
                    return Ok(());
                }

                let Some(call) = self
                    .repo
                    .get_call_by_room_name(room_name)
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?
                else {
                    // Call already archived, nothing to do.
                    return Ok(());
                };

                if let Some(participant_identity) = &event.participant_identity {
                    self.repo
                        .remove_participant(&call.id, participant_identity.copied())
                        .await
                        .map_err(|e| CallError::Internal(e.into()))?;
                    let mut metadata = CallNotificationMetadata::new(call.id, call.channel_id);
                    metadata.identity = Some(participant_identity.to_string());
                    metadata.user_id = Some(participant_identity.to_string());
                    self.publish_call_notification(CallNotificationEvent::ParticipantLeft(
                        metadata,
                    ));
                } else if let Some(identity) = &event.guest_identity {
                    self.repo
                        .reconcile_guest(&call.id, *identity, false)
                        .await?;
                    let mut metadata = CallNotificationMetadata::new(call.id, call.channel_id);
                    metadata.identity = Some(identity.to_string());
                    self.publish_call_notification(CallNotificationEvent::ParticipantLeft(
                        metadata,
                    ));
                }

                self.finish_empty_call(&call).await?;
            }
            "egress_started" | "egress_updated" => {
                tracing::info!(
                    event_type = %event.event,
                    egress_id = ?event.egress_id,
                    room_name = ?event.room_name,
                    "egress event"
                );
                // `egress_started` carries the wall-clock instant the encoder
                // actually began capturing. Persist it so the frontend can
                // anchor transcript-to-audio sync to the recording's true
                // origin instead of the call-creation timestamp (which lags
                // the recording start by the egress bootstrap window).
                if event.event == "egress_started" {
                    if let Some(egress_id) = &event.egress_id {
                        let started_at =
                            chrono::DateTime::<chrono::Utc>::from_timestamp(event.created_at, 0);
                        if let Some(started_at) = started_at {
                            self.repo
                                .set_recording_started_at_by_egress_id(egress_id, started_at)
                                .await
                                .map_err(|e| CallError::Internal(e.into()))?;
                        } else {
                            tracing::warn!(
                                egress_id,
                                created_at = event.created_at,
                                "egress_started webhook had unparseable created_at",
                            );
                        }
                    } else {
                        tracing::warn!("egress_started webhook missing egress_id");
                    }
                }
            }
            "egress_ended" => {
                let (Some(egress_id), Some(file_url)) = (&event.egress_id, &event.file_url) else {
                    tracing::warn!("egress_ended webhook missing egress_id or file_url");
                    return Ok(());
                };

                let recording_key = extract_recording_key(file_url);
                tracing::info!(egress_id, recording_key, "egress recording completed");

                // Find the archived call record by egress_id and update the recording key.
                if let Some((call_id, channel_id)) = self
                    .repo
                    .get_call_record_by_egress_id(egress_id)
                    .await
                    .map_err(|e| CallError::Internal(e.into()))?
                {
                    self.repo
                        .set_recording_key(&call_id, recording_key)
                        .await
                        .map_err(|e| CallError::Internal(e.into()))?;
                    self.publish_call_event(&CallMacroEvent::recording_ready(
                        CallRecordingReadyMetadata {
                            call_id,
                            channel_id,
                        },
                    ));
                    self.publish_call_notification(CallNotificationEvent::RecordingReady(
                        CallNotificationMetadata::new(call_id, None),
                    ));
                } else {
                    // Call not yet archived — store on the active call so
                    // archive_call can carry it forward.
                    let updated = self
                        .repo
                        .set_active_call_recording_key(egress_id, recording_key)
                        .await
                        .map_err(|e| CallError::Internal(e.into()))?;
                    if !updated {
                        tracing::warn!(
                            egress_id,
                            "no active call or call record found for egress_id"
                        );
                    }
                }
            }
            _ => {
                tracing::debug!(event_type = %event.event, "unhandled webhook event type");
            }
        }

        Ok(())
    }

    #[tracing::instrument(err, skip(self))]
    async fn get_call_record(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<CallRecord, CallError> {
        let mut record = authorized_call_record(&self.repo, &receipt).await?;
        let user_id = receipt
            .get_authenticated_user()
            .map_err(|_| CallError::Auth)?;

        if let Some(recording_key) = &record.recording_key {
            record.recording_url = self
                .recording_storage
                .presign_recording_url(recording_key)
                .await
                .inspect_err(|e| tracing::error!(error=?e, "failed to presign recording URL"))
                .ok();
        }

        if let Some(preview_key) = &record.preview_key {
            record.recording_preview_url = self
                .recording_storage
                .presign_recording_preview_url(preview_key)
                .await
                .inspect_err(
                    |e| tracing::error!(error=?e, "failed to presign recording preview URL"),
                )
                .ok();
        }

        // Only active calls keep decline rows; archived calls drop them with
        // the call, and an inactive record already resolves as ended.
        record.viewer_has_declined = if record.is_active {
            self.repo
                .has_declined(&record.call_id, user_id.as_ref())
                .await
                .map_err(|e| CallError::Internal(e.into()))?
        } else {
            false
        };

        Ok(record)
    }

    #[tracing::instrument(err, skip(self, receipt), fields(call.id = %receipt.entity().entity_id))]
    async fn get_call_recording(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<RecordingDownload, CallError> {
        let record = authorized_call_record(&self.repo, &receipt).await?;
        let key = record
            .recording_key
            .ok_or_else(|| CallError::NotFound(record.call_id.to_string()))?;

        self.recording_storage
            .open_recording(&key)
            .await
            .map_err(CallError::Internal)?
            .ok_or_else(|| CallError::NotFound(record.call_id.to_string()))
    }

    #[tracing::instrument(err, skip(self))]
    async fn delete_call_record(
        &self,
        receipt: EntityAccessReceipt<EditAccessLevel>,
    ) -> Result<(), CallError> {
        let entity = receipt.entity();
        if entity.entity_type != EntityType::Call {
            return Err(CallError::Internal(anyhow::anyhow!(
                "expected Call entity in receipt, got {:?}",
                entity.entity_type
            )));
        }
        let call_id = Uuid::parse_str(&entity.entity_id)
            .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;
        let actor_user_id = event_actor_user_id(receipt.auth());

        // Look up channel_id before deletion so the deleted event includes channel context.
        let channel_id = self
            .repo
            .get_call_record_by_call_id(&call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .map(|r| r.channel_id);

        let storage_keys = self
            .repo
            .delete_call_record(&call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;

        if storage_keys.is_some()
            && let Some(channel_id) = channel_id
        {
            self.publish_call_event(&CallMacroEvent::record_deleted(CallRecordDeletedMetadata {
                call_id,
                channel_id,
                actor_user_id,
            }));
        }

        if let Some(storage_keys) = storage_keys {
            if let Some(key) = storage_keys.recording_key.as_deref() {
                self.recording_storage
                    .delete_recording(key)
                    .await
                    .inspect_err(|e| {
                        tracing::error!(error=?e, recording_key=%key, "failed to delete call recording from storage");
                    })
                    .ok();
            }

            let preview_keys = match storage_keys.preview_key {
                Some(preview_key) => vec![preview_key],
                None => storage_keys
                    .recording_key
                    .as_deref()
                    .map(derive_preview_keys_from_recording_key)
                    .unwrap_or_default(),
            };

            for preview_key in preview_keys {
                self.recording_storage
                    .delete_recording_preview(&preview_key)
                    .await
                    .inspect_err(|e| {
                        tracing::error!(error=?e, preview_key=%preview_key, "failed to delete call recording preview from storage");
                    })
                    .ok();
            }
        }

        Ok(())
    }

    #[tracing::instrument(err, skip(self, segment))]
    async fn ingest_transcript_segment(
        &self,
        room_name: &Uuid,
        segment: TranscriptSegmentRequest,
    ) -> Result<(), CallError> {
        if !segment.is_final {
            return Ok(());
        }

        let call = self
            .repo
            .get_call_by_room_name(&room_name.to_string())
            .await
            .map_err(|e| CallError::Internal(e.into()))?
            .ok_or_else(|| CallError::NotFound(room_name.to_string()))?;

        // Attach a stable voice id to each transcript row. Reuse an earlier
        // voice id for the same diarized speaker in this call before falling
        // back to embedding-based upsert; this prevents creating a fresh
        // `voice.id` for every finalized utterance from the same user.
        // Failure to persist the embedding must not block transcript ingest —
        // log and continue without a voice id.
        let voice_id = match segment.embedding.as_deref() {
            Some(embedding) if !embedding.is_empty() => {
                let existing_voice_id = self
                    .repo
                    .get_transcript_voice_id_for_speaker(
                        &call.id,
                        &segment.speaker_id,
                        segment.diarized_speaker_id.as_deref(),
                    )
                    .await
                    .inspect_err(|e| {
                        tracing::error!(error=?e, "failed to look up existing speaker voice id")
                    })
                    .ok()
                    .flatten();

                match existing_voice_id {
                    Some(voice_id) => Some(voice_id),
                    None => self
                        .voice_repo
                        .upsert_voice(embedding)
                        .await
                        .inspect_err(
                            |e| tracing::error!(error=?e, "failed to upsert voice embedding"),
                        )
                        .ok(),
                }
            }
            _ => None,
        };

        self.repo
            .create_transcript_segment(&call.id, &segment, voice_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;

        Ok(())
    }

    #[tracing::instrument(err, skip(self))]
    async fn edit_call_record(
        &self,
        receipt: EntityAccessReceipt<EditAccessLevel>,
        request: EditCallRecordRequest,
    ) -> Result<(), CallError> {
        let entity = receipt.entity();
        if entity.entity_type != EntityType::Call {
            return Err(CallError::Internal(anyhow::anyhow!(
                "expected Call entity in receipt, got {:?}",
                entity.entity_type
            )));
        }

        let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
            .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
        let actor_user_id = event_actor_user_id(receipt.auth());

        let record = self
            .repo
            .get_call_record_by_call_id(&call_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        let team_share_request = TeamShareRequest {
            access_level: request
                .share_permission
                .as_ref()
                .and_then(|p| p.team_share_access_level),
            legacy_enabled: request.share_with_team,
        };
        if let Some(record) = &record
            && !super::models::permitted_team_memory_intent(record.channel_id, true)
            && live_share_intent(team_share_request)? == Some(true)
        {
            return Err(CallError::Forbidden(
                "Calls without a channel cannot be included in team memory".to_string(),
            ));
        }
        let custom_name = request.custom_name.clone();
        let mut share_permission = request.share_permission;

        // While the call is live, team sharing is the pending toggle on the
        // active call (any Edit-level caller may flip it, like the toggle
        // endpoint); it becomes canonical state when the call is archived.
        // Once archived, the change is authorized against the persisted
        // creator before any write, so a rejected request publishes nothing.
        let live_share_with_team = match &record {
            Some(record) if record.is_active => live_share_intent(team_share_request)?,
            _ => None,
        };
        let team_share = if live_share_with_team.is_some() {
            // The repository refuses a team level without a command; the live
            // intent is carried separately.
            if let Some(permission) = share_permission.as_mut() {
                permission.team_share_access_level = None;
            }
            None
        } else {
            self.authorize_call_team_share(&receipt, &call_id, team_share_request)
                .await?
        };
        // Events report the committed team-share outcome, never the raw request.
        let share_with_team = live_share_with_team.or_else(|| {
            team_share
                .as_ref()
                .map(|command| command.target().is_some())
        });

        self.repo
            .patch_call_record(
                &call_id,
                &EditCallRecordRepoArgs {
                    share_permission,
                    custom_name: request.custom_name,
                    team_share,
                    live_share_with_team,
                },
            )
            .await?;

        let Some(record) = record else {
            return Ok(());
        };

        self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
            call_id,
            channel_id: record.channel_id,
            actor_user_id,
            custom_name,
            share_with_team,
        }));

        // Participants of an in-progress call mirror the pending toggle in
        // their call UI; tell them when it changed.
        if let Some(share_with_team) = live_share_with_team {
            self.send_call_participant_event(
                &call_id,
                "call_share_with_team_toggled",
                &serde_json::json!({
                    "call_id": call_id,
                    "channel_id": record.channel_id,
                    "share_with_team": share_with_team,
                    "toggled_by": receipt.get_authenticated_user().ok(),
                }),
            )
            .await;
        }

        Ok(())
    }

    #[tracing::instrument(err, skip(self))]
    async fn toggle_share_with_team(
        &self,
        receipt: EntityAccessReceipt<EditAccessLevel>,
    ) -> Result<bool, CallError> {
        let entity = receipt.entity();
        if entity.entity_type != EntityType::Call {
            return Err(CallError::Internal(anyhow::anyhow!(
                "expected Call entity in receipt, got {:?}",
                entity.entity_type
            )));
        }

        let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
            .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
        let actor_user_id = event_actor_user_id(receipt.auth());

        let record = self
            .repo
            .get_call_record_by_call_id(&call_id)
            .await
            .map_err(|error| CallError::Internal(error.into()))?
            .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;
        if !record.is_active {
            return Err(CallError::Conflict(
                "Only active calls have a team memory toggle".to_string(),
            ));
        }
        let (new_value, channel_id) = if record.channel_id.is_none() {
            if !record.share_with_team {
                return Err(CallError::Forbidden(
                    "Calls without a channel cannot be included in team memory".to_string(),
                ));
            }
            // Permit clearing an old standalone intent without a read/flip race
            // that could accidentally re-enable it in another request.
            self.repo
                .patch_call_record(
                    &call_id,
                    &EditCallRecordRepoArgs {
                        share_permission: None,
                        custom_name: None,
                        team_share: None,
                        live_share_with_team: Some(false),
                    },
                )
                .await?;
            (false, None)
        } else {
            self.repo.toggle_share_with_team(&call_id).await?
        };

        self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
            call_id,
            channel_id,
            actor_user_id,
            custom_name: None,
            share_with_team: Some(new_value),
        }));

        self.send_call_participant_event(
            &call_id,
            "call_share_with_team_toggled",
            &serde_json::json!({
                "call_id": call_id,
                "channel_id": channel_id,
                "share_with_team": new_value,
                "toggled_by": receipt.get_authenticated_user().ok(),
            }),
        )
        .await;

        Ok(new_value)
    }

    #[tracing::instrument(err, skip(self, request), fields(num_assignments = request.assignments.len()))]
    async fn edit_call_transcript(
        &self,
        receipt: EntityAccessReceipt<EditAccessLevel>,
        request: EditCallTranscriptRequest,
    ) -> Result<(), CallError> {
        let entity = receipt.entity();
        if entity.entity_type != EntityType::Call {
            return Err(CallError::Internal(anyhow::anyhow!(
                "expected Call entity in receipt, got {:?}",
                entity.entity_type
            )));
        }

        let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
            .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;

        self.repo
            .patch_call_transcript_custom_speakers(&call_id, &request.assignments)
            .await
            .map_err(|e| CallError::Internal(e.into()))
    }

    #[tracing::instrument(err, skip(self, request, user_id), fields(num_call_ids = request.call_ids.len()))]
    async fn get_batch_call_record_previews<'a>(
        &self,
        request: GetBatchCallRecordPreviewRequest,
        user_id: MacroUserIdStr<'a>,
    ) -> Result<GetBatchCallRecordPreviewResponse, CallError> {
        let previews = self
            .repo
            .batch_get_call_record_previews(&request.call_ids, user_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        Ok(GetBatchCallRecordPreviewResponse { previews })
    }

    #[tracing::instrument(err, skip(self))]
    async fn summarize_call(&self, call_id: &Uuid) -> Result<(), CallError> {
        // No summarizer configured — feature is off, silently succeed.
        let Some(summarizer) = self.summarizer.as_ref() else {
            return Ok(());
        };

        if let Err(e) = generate_and_persist_custom_speakers(&self.repo, summarizer, call_id).await
        {
            tracing::error!(error=?e, %call_id, "failed to generate custom speakers before summarization");
        }

        // Load the finalized call record after the custom-speaker step so the
        // summary prompt sees any newly persisted speaker overrides. May race
        // with deletion, in which case there's nothing to summarize — log and
        // move on.
        let Some(record) = self
            .repo
            .get_call_record_by_call_id(call_id)
            .await
            .inspect_err(|e| tracing::error!(error=?e, %call_id, "failed to load call record for summarization"))
            .map_err(|e| CallError::Internal(e.into()))?
        else {
            tracing::warn!(%call_id, "call record not found for summarization; skipping");
            return Ok(());
        };

        if record.transcript.is_empty() {
            tracing::info!(%call_id, "call has empty transcript; skipping summarization");
            return Ok(());
        }

        let Some(summary) = summarizer
            .summarize_call(
                call_id,
                summary_transcript(record.transcript, &record.guests),
            )
            .await
            .inspect_err(|e| tracing::error!(error=?e, %call_id, "call summarizer failed"))
            .map_err(|e| CallError::Internal(e.into()))?
        else {
            tracing::info!(
                %call_id,
                "summarizer returned no summary (uninformative transcript); skipping persistence"
            );
            return Ok(());
        };

        let summary_persisted = self
            .repo
            .insert_call_summary(call_id, &summary)
            .await
            .inspect_err(|e| tracing::error!(error=?e, %call_id, "failed to persist call summary"))
            .map_err(|e| CallError::Internal(e.into()))?;

        let ai_name_generated = generate_and_persist_call_name(
            &self.repo,
            summarizer,
            call_id,
            &summary,
            record.custom_name.is_none(),
        )
        .await;

        if summary_persisted {
            self.publish_call_event(&CallMacroEvent::record_summarized(
                CallRecordSummarizedMetadata {
                    call_id: *call_id,
                    channel_id: record.channel_id,
                    ai_name_generated,
                },
            ));
            self.publish_call_notification(CallNotificationEvent::Summarized(
                CallNotificationMetadata::new(*call_id, None),
            ));
        }

        Ok(())
    }

    #[tracing::instrument(err, skip(self))]
    async fn get_user_voices(&self, macro_user_id: &Uuid) -> Result<Vec<Uuid>, CallError> {
        self.voice_repo
            .get_user_voices(macro_user_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))
    }

    #[tracing::instrument(err, skip(self, embedding))]
    async fn set_user_voice(
        &self,
        macro_user_id: &Uuid,
        embedding: &[f32],
    ) -> Result<Uuid, CallError> {
        let voice_id = self
            .voice_repo
            .upsert_voice(embedding)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        self.voice_repo
            .link_user_voice(macro_user_id, &voice_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))?;
        Ok(voice_id)
    }
}

impl<
    R: CallRepository + Clone,
    C: CallRtcClient,
    Cn: ConnectionService,
    E: EntityAccessService,
    N: NotificationIngress,
    S: RecordingStorage,
    Sm: CallSummarizer + Clone,
    V: VoipPushSender,
    Vr: VoiceRepository + Clone,
    B: MacroEventBroker + Clone,
> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>
{
    /// Fire-and-forget spawn of [`CallService::summarize_call`] for `call_id`.
    ///
    /// Called after the `call_records` row is persisted so that summarization
    /// can run off the request path without blocking call completion. The
    /// spawned task owns cloned handles to `repo`, `summarizer`, and the event
    /// broker; errors are logged, never propagated. When no summarizer is
    /// configured this is a no-op and no task is spawned.
    fn spawn_summarize_call(&self, call_id: Uuid) {
        let Some(summarizer) = self.summarizer.clone() else {
            return;
        };
        let repo = self.repo.clone();
        let event_broker = self.event_broker.clone();
        tokio::spawn(async move {
            if let Err(e) = generate_and_persist_custom_speakers(&repo, &summarizer, &call_id).await
            {
                tracing::error!(error=?e, %call_id, "failed to generate custom speakers before summarization");
            }

            let record = match repo.get_call_record_by_call_id(&call_id).await {
                Ok(Some(record)) => record,
                Ok(None) => {
                    tracing::warn!(%call_id, "call record not found for summarization; skipping");
                    return;
                }
                Err(e) => {
                    tracing::error!(error=?e, %call_id, "failed to load call record for summarization");
                    return;
                }
            };

            if record.transcript.is_empty() {
                tracing::info!(%call_id, "call has empty transcript; skipping summarization");
                return;
            }

            let summary = match summarizer
                .summarize_call(
                    &call_id,
                    summary_transcript(record.transcript, &record.guests),
                )
                .await
            {
                Ok(Some(summary)) => summary,
                Ok(None) => {
                    tracing::info!(
                        %call_id,
                        "summarizer returned no summary (uninformative transcript); skipping persistence"
                    );
                    return;
                }
                Err(e) => {
                    tracing::error!(error=?e, %call_id, "failed to summarize call on completion");
                    return;
                }
            };

            let summary_persisted = match repo.insert_call_summary(&call_id, &summary).await {
                Ok(persisted) => persisted,
                Err(e) => {
                    tracing::error!(error=?e, %call_id, "failed to persist call summary");
                    return;
                }
            };

            let ai_name_generated = generate_and_persist_call_name(
                &repo,
                &summarizer,
                &call_id,
                &summary,
                record.custom_name.is_none(),
            )
            .await;

            if summary_persisted {
                publish_call_event(
                    &event_broker,
                    &CallMacroEvent::record_summarized(CallRecordSummarizedMetadata {
                        call_id,
                        channel_id: record.channel_id,
                        ai_name_generated,
                    }),
                );
                publish_call_notification(
                    &event_broker,
                    CallNotificationEvent::Summarized(CallNotificationMetadata::new(call_id, None)),
                );
            }
        });
    }

    /// Fire-and-forget spawn of finished-call voice enrollment.
    ///
    /// Called from `process_webhook_event` immediately after `archive_call`
    /// finalizes the `call_records` row. Voice ids for consistently diarized
    /// speakers are enrolled for the users who spoke them. This intentionally
    /// does not populate `custom_speaker`; AI speaker attribution is handled
    /// separately before summarization.
    fn spawn_process_voices_for_call(&self, call_record_id: Uuid) {
        let repo = self.repo.clone();
        let voice_repo = self.voice_repo.clone();
        tokio::spawn(async move {
            enroll_stable_speaker_voices_for_call_record(&repo, &voice_repo, call_record_id).await;
        });
    }
}

pub(crate) fn publish_call_event<B: MacroEventBroker>(event_broker: &B, event: &CallMacroEvent) {
    drop(event_broker.send_event(event).inspect_err(|error| {
        tracing::error!(error = ?error, "failed to schedule call lifecycle event");
    }));
}

pub(crate) fn publish_call_notification<B: MacroEventBroker>(
    event_broker: &B,
    event: CallNotificationEvent,
) {
    drop(
        event_broker
            .send_event(&CallNotificationMacroEvent::new(event))
            .inspect_err(|error| {
                tracing::error!(error = ?error, "failed to schedule call notification");
            }),
    );
}

/// Replace guest speaker ids with their display names for the summarizer's
/// input only; the stored transcript keeps the opaque ids.
fn summary_transcript(
    mut transcript: Vec<CallRecordTranscriptSegment>,
    guests: &[super::models::CallRecordGuest],
) -> Vec<CallRecordTranscriptSegment> {
    let names: HashMap<String, &str> = guests
        .iter()
        .map(|guest| (guest.id.to_string(), guest.display_name.as_str()))
        .collect();
    for segment in &mut transcript {
        if let Some(name) = names.get(segment.speaker_id.as_str()) {
            segment.speaker_id = format!("{name} (guest)");
        }
    }
    transcript
}

async fn generate_and_persist_call_name<R, Sm>(
    repo: &R,
    summarizer: &Sm,
    call_id: &Uuid,
    summary: &str,
    should_generate_name: bool,
) -> bool
where
    R: CallRepository,
    Sm: CallSummarizer,
{
    if !should_generate_name {
        return false;
    }

    match summarizer.generate_call_name(call_id, summary).await {
        Ok(Some(name)) => match repo.set_custom_name_if_null(call_id, &name).await {
            Ok(name_persisted) => name_persisted,
            Err(e) => {
                tracing::error!(
                    error=?e, %call_id,
                    "failed to persist ai-generated call name"
                );
                false
            }
        },
        Ok(None) => {
            tracing::info!(
                %call_id,
                "ai call naming returned no title; leaving name unset"
            );
            false
        }
        Err(e) => {
            tracing::error!(
                error=?e, %call_id,
                "ai call naming failed after summary; leaving name unset"
            );
            false
        }
    }
}

async fn generate_and_persist_custom_speakers<R, Sm>(
    repo: &R,
    summarizer: &Sm,
    call_record_id: &Uuid,
) -> anyhow::Result<()>
where
    R: CallRepository,
    Sm: CallSummarizer,
{
    let mut transcripts = repo
        .get_enhanced_call_record_transcripts(call_record_id)
        .await
        .map_err(Into::into)?;
    // Never infer a Macro account identity for a guest speaker.
    transcripts.retain(|segment| {
        super::meetings::GuestId::parse_rtc_identity(&segment.speaker_id).is_none()
    });
    if transcripts.is_empty() {
        tracing::info!(%call_record_id, "call has empty archived transcript; skipping custom speaker generation");
        return Ok(());
    }

    let candidate_speakers = repo
        .get_call_participants_with_team_members(call_record_id)
        .await
        .map_err(Into::into)?;
    if candidate_speakers.is_empty() {
        tracing::info!(%call_record_id, "call has no candidate speakers; skipping custom speaker generation");
        return Ok(());
    }

    let assignments = summarizer
        .generate_custom_speakers(transcripts, candidate_speakers)
        .await
        .map_err(Into::into)?;
    if assignments.is_empty() {
        tracing::info!(%call_record_id, "custom speaker generation returned no assignments");
        return Ok(());
    }

    let num_assignments = assignments.len();
    repo.overwrite_custom_speakers(
        assignments
            .into_iter()
            .map(|result| (result.call_transcript_id, result.custom_speaker))
            .collect(),
    )
    .await
    .map_err(Into::into)?;

    tracing::info!(%call_record_id, num_assignments, "persisted generated custom speaker assignments");
    Ok(())
}

/// Enroll stable speaker voice ids observed in a freshly archived call.
///
/// For each `speaker_id` in the call transcript, the repository returns
/// candidates only when every transcript row for that speaker has the same
/// non-NULL `diarized_speaker_id`. All distinct non-NULL `voice_id`s on those
/// rows are linked to the resolved macro user in `macro_user_voice` via
/// [`VoiceRepository::link_user_voice`].
async fn enroll_stable_speaker_voices_for_call_record<R: CallRepository, Vr: VoiceRepository>(
    repo: &R,
    voice_repo: &Vr,
    call_record_id: Uuid,
) {
    let stable_voices = match repo
        .get_stable_speaker_voices_for_call_record(&call_record_id)
        .await
    {
        Ok(stable_voices) => stable_voices,
        Err(e) => {
            tracing::error!(
                error=?e, %call_record_id,
                "failed to load stable speaker voices for enrollment"
            );
            return;
        }
    };

    if stable_voices.is_empty() {
        return;
    }

    let total = stable_voices.len();
    let mut linked = 0usize;
    for (macro_user_id, voice_id) in stable_voices {
        match voice_repo.link_user_voice(&macro_user_id, &voice_id).await {
            Ok(()) => linked += 1,
            Err(e) => tracing::error!(
                error=?e, %call_record_id, %macro_user_id, %voice_id,
                "failed to link stable speaker voice to user"
            ),
        }
    }

    tracing::info!(
        %call_record_id, linked, total,
        "stable speaker voice enrollment completed"
    );
}

/// Extract the recording key from a full S3 URL.
///
/// Given `https://bucket.s3.amazonaws.com/calls/UUID/TIMESTAMP.mp4`,
/// returns `UUID/TIMESTAMP.mp4`. Falls back to the full URL if it does
/// not contain the `calls/` prefix.
fn extract_recording_key(file_url: &str) -> &str {
    file_url
        .find("calls/")
        .map(|idx| &file_url[idx + "calls/".len()..])
        .unwrap_or(file_url)
}

fn recording_key_parent_and_file_name(recording_key: &str) -> Option<(&str, &str)> {
    let recording_key = recording_key
        .strip_prefix("calls/")
        .unwrap_or(recording_key);
    let (parent, file_name) = recording_key.rsplit_once('/')?;
    if parent.is_empty() || file_name.is_empty() {
        return None;
    }
    Some((parent, file_name))
}

fn derive_preview_key_from_recording_key(recording_key: &str) -> Option<String> {
    let (parent, file_name) = recording_key_parent_and_file_name(recording_key)?;
    let recording_stem = file_name.strip_suffix(".mp4").unwrap_or(file_name);

    Some(format!("calls/{parent}/{recording_stem}/PREVIEW.jpg"))
}

fn derive_preview_keys_from_recording_key(recording_key: &str) -> Vec<String> {
    let Some((parent, file_name)) = recording_key_parent_and_file_name(recording_key) else {
        return Vec::new();
    };
    let Some(preview_key) = derive_preview_key_from_recording_key(recording_key) else {
        return Vec::new();
    };
    let legacy_preview_key = format!("calls/{parent}/{file_name}/PREVIEW.jpg");
    if preview_key == legacy_preview_key {
        vec![preview_key]
    } else {
        vec![preview_key, legacy_preview_key]
    }
}

/// Zero-sized placeholder implementation of [`CallSummarizer`].
///
/// [`CallServiceImpl`]'s summarizer generic defaults to this type so callers
/// that do not wire an AI summarizer can simply leave the `summarizer` field
/// as `None`. The implementation itself is never executed — [`CallServiceImpl`]
/// only invokes `summarize_call` when `summarizer.is_some()`, and this
/// placeholder is exclusively used as the type parameter when the field is
/// `None`. If it is ever called, that is a programming error.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopCallSummarizer;

impl CallSummarizer for NoopCallSummarizer {
    type Err = anyhow::Error;

    async fn summarize_call(
        &self,
        _call_id: &Uuid,
        _transcript: Vec<CallRecordTranscriptSegment>,
    ) -> Result<Option<String>, Self::Err> {
        // Type-placeholder only — [`CallServiceImpl`] must never invoke this
        // when `summarizer` is `None`, and [`NoopCallSummarizer`] is never a
        // `Some(_)` value in practice.
        unreachable!(
            "NoopCallSummarizer::summarize_call invoked; it exists only as a type placeholder when the optional summarizer is None"
        )
    }

    async fn generate_call_name(
        &self,
        _call_id: &Uuid,
        _summary: &str,
    ) -> Result<Option<String>, Self::Err> {
        unreachable!(
            "NoopCallSummarizer::generate_call_name invoked; it exists only as a type placeholder when the optional summarizer is None"
        )
    }

    async fn generate_custom_speakers(
        &self,
        _transcript: Vec<EnrichedCallTranscript>,
        _candidate_speakers: Vec<MacroUserIdStr<'static>>,
    ) -> Result<Vec<CallTranscriptCustomSpeakerResult>, Self::Err> {
        unreachable!(
            "NoopCallSummarizer::generate_custom_speakers invoked; it exists only as a type placeholder when the optional summarizer is None"
        )
    }
}

/// The record a call receipt authorizes, at the receipt's access level, with
/// its channel named as the receipt's user sees it.
async fn authorized_call_record<R: CallRepository>(
    repo: &R,
    receipt: &EntityAccessReceipt<ViewAccessLevel>,
) -> Result<CallRecord, CallError> {
    let entity = receipt.entity();
    if entity.entity_type != EntityType::Call {
        return Err(CallError::Internal(anyhow::anyhow!(
            "expected Call entity in receipt, got {:?}",
            entity.entity_type
        )));
    }
    let call_id = Uuid::parse_str(&entity.entity_id)
        .map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;

    let user_id = receipt
        .get_authenticated_user()
        .map_err(|_| CallError::Auth)?;

    let mut record = repo
        .get_call_record_by_call_id(&call_id)
        .await
        .map_err(|e| CallError::Internal(e.into()))?
        .ok_or_else(|| CallError::NotFound(call_id.to_string()))?;

    record.user_access_level = match receipt.entity_permission() {
        EntityPermission::AccessLevel { access_level } => Some(*access_level),
        _ => None,
    };

    record.channel_name = match record.channel_id {
        Some(channel_id) => repo
            .resolve_channel_name(&channel_id, user_id.copied())
            .await
            .map_err(|e| CallError::Internal(e.into()))?,
        None => None,
    };

    Ok(record)
}

/// Lightweight implementation of [`CallRecordQueryService`] and
/// [`CallRecordReader`] for read-only call record queries. Unlike
/// [`CallServiceImpl`], this only requires a repository — no RTC client,
/// notifications, or entity access.
pub struct CallRecordQueryServiceImpl<R: CallRepository> {
    repo: R,
}

impl<R: CallRepository> CallRecordQueryServiceImpl<R> {
    /// Create a new query service with the given repository.
    pub fn new(repo: R) -> Self {
        Self { repo }
    }
}

impl<R: CallRepository> CallRecordQueryService for CallRecordQueryServiceImpl<R> {
    #[tracing::instrument(err, skip(self))]
    async fn get_user_call_records(
        &self,
        req: GetCallRecordsRequest,
    ) -> Result<Vec<CallRecord>, CallError> {
        let filter = req.query.filter();
        let page = CallRecordPage::from_query(&req.query);
        self.repo
            .get_call_records_by_user(req.user_id.copied(), req.limit, filter, page)
            .await
            .map_err(|e| CallError::Internal(e.into()))
    }
    #[tracing::instrument(err, skip(self))]
    async fn get_call_record_people(&self, call_record_id: Uuid) -> Result<CallPeople, CallError> {
        self.repo
            .get_call_record_people(&call_record_id)
            .await
            .map_err(|e| CallError::Internal(e.into()))
    }
}

impl<R: CallRepository> CallRecordReader for CallRecordQueryServiceImpl<R> {
    #[tracing::instrument(err, skip(self))]
    async fn get_call_record(
        &self,
        receipt: EntityAccessReceipt<ViewAccessLevel>,
    ) -> Result<CallRecord, CallError> {
        authorized_call_record(&self.repo, &receipt).await
    }
}