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.

36.9 KB
Raw Blame
//! Domain models for the call crate.

use std::fmt;

use chrono::{DateTime, Utc};
use item_filters::{
    CallStatus,
    ast::{LiteralTree, call::CallLiteral},
};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{Query, SimpleSortMethod};
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::team_share::{
    AuthorizedTeamShareCommand, TeamSharePolicyError,
};
use uuid::Uuid;

/// Represents an active call in a channel.
#[derive(Debug, Clone)]
pub struct Call {
    /// Unique call identifier.
    pub id: Uuid,
    /// The channel this call belongs to.
    pub channel_id: Option<Uuid>,
    /// Name of the RTC room, unique per call session.
    pub room_name: String,
    /// User who created the call.
    pub created_by: String,
    /// When the call was created.
    pub created_at: DateTime<Utc>,
    /// Egress (recording) ID, if recording is active.
    pub egress_id: Option<String>,
}

/// Where a call's discussion lives, decided once when the call is created.
/// `channel_id` cannot decide this: past channel calls keep their own thread.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CallDiscussion {
    /// A thread in the call's channel, rooted at the message with the call's id.
    ChannelThread {
        /// The channel holding the thread.
        channel_id: Uuid,
        /// The thread's root message.
        root_id: Uuid,
    },
    /// The call's own thread on the call parent.
    CallChat {
        /// The call owning the thread.
        call_id: Uuid,
    },
}

impl CallDiscussion {
    /// Read the stored value. A channel thread whose channel is gone has nothing
    /// left to show, and reads as a call with no chat.
    pub fn from_stored(stored: &str, call_id: Uuid, channel_id: Option<Uuid>) -> Self {
        match (stored, channel_id) {
            ("channel_thread", Some(channel_id)) => Self::ChannelThread {
                channel_id,
                root_id: call_id,
            },
            _ => Self::CallChat { call_id },
        }
    }
}

/// Facts committed when an active call is archived.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArchivedCall {
    /// The archived call record identifier.
    pub call_id: Uuid,
    /// The channel the call belongs to.
    pub channel_id: Option<Uuid>,
    /// User who created the call.
    pub created_by: String,
    /// When the call started.
    pub started_at: DateTime<Utc>,
    /// When the call ended.
    pub ended_at: DateTime<Utc>,
    /// Call duration in milliseconds.
    pub duration_ms: i64,
    /// Whether a recording egress was started before the call was archived.
    pub has_recording: bool,
    /// Macro accounts that joined the call over its lifetime, once each.
    pub participants: Vec<String>,
    /// Whether the call's discussion is a thread in its channel.
    pub channel_thread: bool,
}

/// The people known to have been on, or invited to, an archived call.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CallPeople {
    /// Macro accounts that joined the call, plus the owner of its meeting link.
    pub user_ids: Vec<MacroUserIdStr<'static>>,
    /// Email addresses invited to the calendar event carrying the call's
    /// meeting link. External guests join without an account, so this is the
    /// only record of who they are.
    pub invitee_emails: Vec<String>,
}

/// A participant in an active call.
#[derive(Debug, Clone)]
pub struct CallParticipant {
    /// The call this participant is in.
    pub call_id: Uuid,
    /// The user id.
    pub user_id: String,
    /// When the user joined the call.
    pub joined_at: DateTime<Utc>,
}

/// Response returned when creating or joining a call.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallTokenResponse {
    /// Whether this request allocated the call.
    pub started: bool,
    /// RTC participant identity.
    pub participant_id: String,
    /// Meeting link capability, when joined using a link.
    pub share_token: Option<String>,
    /// The call identifier.
    pub call_id: Uuid,
    /// The channel this call is associated with.
    pub channel_id: Option<Uuid>,
    /// The RTC token for connecting to the room.
    pub token: String,
    /// The RTC room name.
    pub room_name: String,
    /// The RTC server URL for the frontend SDK to connect to.
    pub server_url: String,
}

/// Options for an authenticated call join.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct JoinCallRequest {
    /// What to do when this account is participating in another call.
    #[serde(default)]
    pub on_other_call: OnOtherCall,
    /// Disconnect an existing RTC connection for this identity.
    #[serde(default)]
    pub replace: bool,
    /// Optional display name in the RTC room.
    pub name: Option<String>,
}

impl JoinCallRequest {
    /// The app's join: switch out of any other call and reclaim this identity.
    pub fn for_app() -> Self {
        Self {
            on_other_call: OnOtherCall::Switch,
            replace: true,
            name: None,
        }
    }
}

/// Whether a live call is associated with a channel.
#[derive(Debug, Clone, Copy, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum LiveCallKind {
    /// Call associated with a channel.
    Channel,
    /// Independent meeting call.
    Standalone,
}

/// A live call visible to an account that can join it.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct LiveCallSummary {
    /// Session identifier.
    pub call_id: Uuid,
    /// Channel or standalone call.
    pub kind: LiveCallKind,
    /// Channel identifier, if present.
    pub channel_id: Option<Uuid>,
    /// Invitation identifier, if present.
    pub meeting_id: Option<Uuid>,
    /// Invitation capability, if present.
    pub share_token: Option<String>,
    /// Invitation title, if present.
    pub title: Option<String>,
    /// Caller identifier.
    pub created_by: String,
    /// When the session was created.
    pub created_at: DateTime<Utc>,
    /// Number of active people and guests.
    pub participant_count: i64,
    /// Whether this account is currently being rung.
    pub ringing: bool,
}

/// Response containing every live call this account may join.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct LiveCallsResponse {
    /// Joinable live calls.
    pub calls: Vec<LiveCallSummary>,
}

/// A live media track.
#[derive(Debug, Clone, Copy, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum LiveTrackSource {
    /// Microphone audio.
    Microphone,
    /// Camera video.
    Camera,
    /// Screen video.
    ScreenShare,
    /// Screen audio.
    ScreenShareAudio,
    /// Unrecognized source.
    Unknown,
}

/// Participant kind in the live room.
#[derive(Debug, Clone, Copy, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum LiveParticipantKind {
    /// Signed-in account.
    User,
    /// Link guest.
    Guest,
    /// Bot identity.
    Bot,
}

/// A live media track.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct LiveCallTrack {
    /// Microphone, camera, or screen source.
    pub source: LiveTrackSource,
    /// Whether the track is muted.
    pub muted: bool,
}

/// A connected participant in an RTC room.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct LiveCallParticipant {
    /// RTC identity.
    pub identity: String,
    /// Name displayed to room members.
    pub display_name: String,
    /// User or guest.
    pub kind: LiveParticipantKind,
    /// Macro account identifier, if this is a user.
    pub user_id: Option<String>,
    /// Whether the caller is a program.
    pub is_program: bool,
    /// RTC connection time.
    pub joined_at: Option<DateTime<Utc>>,
    /// Published media tracks.
    pub tracks: Vec<LiveCallTrack>,
}

/// A live RTC room roster.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct LiveCallParticipantsResponse {
    /// Connected participants.
    pub participants: Vec<LiveCallParticipant>,
}

/// Policy for another active call.
#[derive(Debug, Clone, Copy, Default, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum OnOtherCall {
    /// Preserve the other call and return a conflict.
    #[default]
    Fail,
    /// Leave the other call before joining.
    Switch,
}

/// Inputs required by the RTC adapter to produce native VoIP invite payloads.
pub struct VoipPushPayloadRequest<'a> {
    /// Users with resolved PushKit endpoints that should receive native VoIP invites.
    pub recipients: &'a [MacroUserIdStr<'static>],
    /// RTC room name the recipient will join.
    pub room_name: &'a str,
    /// Call record ID exposed to the client.
    pub call_id: Uuid,
    /// Channel ID associated with the call.
    pub channel_id: &'a str,
    /// Channel display name shown in the native incoming-call UI.
    pub channel_name: &'a str,
    /// Caller display name shown in the native incoming-call UI.
    pub caller_name: &'a str,
    /// RTC server URL the native client should connect to.
    pub livekit_server_url: &'a str,
    /// Absolute URL the native client polls while ringing to learn whether
    /// the call was answered elsewhere or ended. `None` when the service has
    /// no public base URL configured.
    pub ring_status_url: Option<&'a str>,
}

/// Per-user status of an incoming-call ring, as reported by the
/// ring-status endpoint while a native client is ringing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum RingStatus {
    /// The call is active and this user has not joined yet — keep ringing.
    Ringing,
    /// This user joined the call on some device — stop ringing (answered elsewhere).
    Answered,
    /// This user declined the call on some device — stop ringing (declined elsewhere).
    Declined,
    /// The call is over (or was replaced by a newer call) — stop ringing (remote ended).
    Ended,
}

/// Response body for `GET /call/ring-status/{call_id}`.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct RingStatusResponse {
    /// The ring status for the authenticated user.
    pub status: RingStatus,
}

/// Identity and room grant extracted from a verified RTC access token.
#[derive(Debug, Clone)]
pub struct VerifiedRingToken {
    /// The participant identity the token was minted for (a Macro user id string).
    pub identity: String,
    /// The room the token grants access to, if any.
    pub room: Option<String>,
}

/// An RTC room that currently exists on the provider.
#[derive(Debug, Clone)]
pub struct RtcRoom {
    /// The room name; Macro names rooms after their call id.
    pub name: String,
    /// When the provider created the room.
    pub created_at: DateTime<Utc>,
}

/// Response for the leave/end call operation.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct LeaveCallResponse {
    /// Whether the entire call was ended (room deleted).
    pub call_ended: bool,
}

/// Response indicating whether an active call exists for a channel.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallActiveResponse {
    /// The call identifier.
    pub call_id: Uuid,
    /// The channel this call belongs to.
    pub channel_id: Uuid,
    /// User who created the call.
    pub created_by: String,
    /// When the call was created.
    pub created_at: DateTime<Utc>,
}

/// A currently active call, as returned by the batch active-calls listing.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ActiveCallSummary {
    /// The call identifier.
    pub call_id: Uuid,
    /// The channel this call belongs to.
    pub channel_id: Uuid,
    /// User who created the call.
    pub created_by: String,
    /// When the call was created.
    pub created_at: DateTime<Utc>,
    /// Number of active participants. Always >= 1 — calls with no active
    /// participants (e.g. orphaned by a dropped RTC webhook) are excluded.
    pub participant_count: i64,
}

/// Response listing all active calls in channels the caller is a member of.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ActiveCallsResponse {
    /// The active calls, newest first.
    pub calls: Vec<ActiveCallSummary>,
}

/// Configuration for S3 egress output.
#[derive(Clone)]
pub struct EgressS3Config {
    /// S3 bucket name.
    pub bucket: String,
    /// AWS region.
    pub region: String,
    /// AWS access key ID.
    pub access_key: String,
    /// AWS secret access key.
    pub secret: String,
}

impl fmt::Debug for EgressS3Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EgressS3Config")
            .field("bucket", &self.bucket)
            .field("region", &self.region)
            .field("access_key", &"<redacted>")
            .field("secret", &"<redacted>")
            .finish()
    }
}

/// A validated webhook event from the RTC provider.
#[derive(Debug, Clone)]
pub struct CallWebhookEvent {
    /// The event type (e.g. `room_started`, `room_finished`, `participant_joined`).
    pub event: String,
    /// Unique event identifier.
    pub id: String,
    /// Room name associated with the event, if any.
    pub room_name: Option<String>,
    /// Participant identity associated with the event, if any.
    pub participant_identity: Option<MacroUserIdStr<'static>>,
    /// Bot identity, classified separately so it never becomes attendance.
    pub bot_identity: Option<bot_id::BotId>,
    /// Non-account guest identity, classified separately from Macro users.
    pub guest_identity: Option<super::meetings::GuestId>,
    /// Egress ID associated with the event, if any.
    pub egress_id: Option<String>,
    /// File download URL from a completed egress, if any.
    pub file_url: Option<String>,
    /// Unix timestamp (seconds) when the event was created.
    pub created_at: i64,
}

/// A transcript segment from LiveKit Inference STT.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct TranscriptSegmentRequest {
    /// LiveKit segment ID (used for deduplication across multiple submitters).
    pub segment_id: String,
    /// The speaker's user ID (from `lk.transcribed_track_id`).
    pub speaker_id: String,
    /// Stable per-speaker identifier produced by the STT provider's diarization
    /// pass. Namespaced upstream by audio track so values are unique across all
    /// tracks in a call. `None` when the provider didn't return a speaker label.
    #[serde(default)]
    pub diarized_speaker_id: Option<String>,
    /// The transcribed text content.
    pub content: String,
    /// When the speaker started talking for this segment.
    pub started_at: DateTime<Utc>,
    /// When the speaker stopped talking for this segment.
    pub ended_at: Option<DateTime<Utc>>,
    /// Whether this is a final transcription (not interim).
    pub is_final: bool,
    /// Wall-clock when the transcriber's STT stream first received audio
    /// for this participant. The server takes the earliest non-null value
    /// across all participants and uses it to overwrite the
    /// `egress_started`-derived `recording_started_at`, which is too early
    /// (it stamps egress bootstrap, not first audio frame).
    #[serde(default)]
    pub stream_started_at: Option<DateTime<Utc>>,
    /// Speaker voice embedding computed by the transcription agent
    /// (e.g. a Resemblyzer 256-dim vector). When present, the server
    /// upserts a `voice` row and stores the resulting id on the transcript
    /// segment so the call-finished pipeline can match it to enrolled users.
    #[serde(default)]
    pub embedding: Option<Vec<f32>>,
}

/// Full archived transcript row used by the AI speaker-attribution pipeline.
///
/// This mirrors every column currently stored in `call_record_transcripts` so
/// the AI adapter can reason from both the raw archived speaker data and any
/// existing overrides.
#[derive(Debug, Clone, serde::Serialize)]
pub struct EnrichedCallTranscript {
    /// Stable DB-row id for this archived transcript segment.
    pub id: Uuid,
    /// The archived call record this transcript row belongs to.
    pub call_record_id: Uuid,
    /// LiveKit segment ID, when the archived row has one.
    pub segment_id: Option<String>,
    /// The speaker's original user ID from the transcribed track.
    pub speaker_id: String,
    /// Stable diarization label emitted by the STT provider, when present.
    pub diarized_speaker_id: Option<String>,
    /// Existing custom speaker override, when one has already been assigned.
    pub custom_speaker: Option<String>,
    /// Speaker voice id attached to the transcript row, when available.
    pub voice_id: Option<Uuid>,
    /// The transcribed text content.
    pub content: String,
    /// When the speaker started this segment.
    pub started_at: DateTime<Utc>,
    /// When the speaker stopped this segment, if known.
    pub ended_at: Option<DateTime<Utc>>,
    /// Ordering within the archived call.
    pub sequence_num: i32,
}

/// Backwards-compatible name for callers that refer to the AI transcript input
/// as "enhanced" rather than "enriched".
pub type EnhancedCallTranscript = EnrichedCallTranscript;

/// AI-generated speaker attribution for one archived transcript row.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct CallTranscriptCustomSpeakerResult {
    /// The call transcript id.
    #[serde(alias = "callTranscriptId")]
    pub call_transcript_id: Uuid,
    /// The custom speaker override for the transcript.
    #[serde(alias = "customSpeaker")]
    pub custom_speaker: String,
}

/// Edit call request, as supplied by inbound callers.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct EditCallRecordRequest {
    /// Updated share permissions. `teamShareAccessLevel` shares the call with
    /// the creator's team and only accepts `view` or `null` (revoke). While
    /// the call is live it sets the pending share-with-team toggle, which is
    /// applied when the call is archived; afterwards only the call's creator
    /// may change it.
    pub share_permission:
        Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,
    /// Deprecated alias for `sharePermission.teamShareAccessLevel`:
    /// `Some(true)` behaves like `"view"`, `Some(false)` like `null`, and
    /// `None` is a no-op. Supplying both with disagreeing values is rejected.
    /// The team is resolved from the call's `created_by`, not the acting user.
    pub share_with_team: Option<bool>,
    /// Updated user-supplied display name for the call. `None` is a no-op;
    /// `Some("")` clears `call_records.custom_name`; any other `Some(s)`
    /// overwrites it with `s`. Only the archived `call_records` row carries
    /// this column — patching while the call is still active is a no-op for
    /// this field.
    pub custom_name: Option<String>,
}

/// Arguments the domain service hands to the repository when editing a call.
///
/// Only the service can produce the authorized team-share command, so inbound
/// callers cannot request a team grant the owner policy has not approved.
#[derive(Debug)]
pub struct EditCallRecordRepoArgs {
    /// Share permission updates, if changing (link and channel sharing).
    pub share_permission:
        Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,
    /// Display name update; see [`EditCallRecordRequest::custom_name`].
    pub custom_name: Option<String>,
    /// Creator-authorized canonical team-share write for an archived call,
    /// present only when the request carried an explicit
    /// `teamShareAccessLevel` or the legacy `shareWithTeam`.
    pub team_share: Option<AuthorizedTeamShareCommand>,
    /// Pending share-with-team intent for a call that is still live; applied
    /// as canonical team sharing when the call is archived.
    pub live_share_with_team: Option<bool>,
}

/// One per-diarized-speaker override, used in [`EditCallTranscriptRequest`].
///
/// `custom_speaker = None` clears any existing override for this
/// `diarized_speaker_id`; `Some(macro_user_id)` sets it. The string is
/// expected to parse as a `MacroUserId` (e.g. `macro|[email protected]`);
/// the service layer rejects malformed values with `400 Bad Request`.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CustomSpeakerAssignment {
    /// The diarization label whose rows this assignment targets.
    pub diarized_speaker_id: String,
    #[cfg_attr(feature = "inbound", schema(value_type = String))]
    /// Macro user id to attribute matching rows to, or `None` to clear.
    pub custom_speaker: Option<MacroUserIdStr<'static>>,
}

/// Body of `PATCH /call/record/{call_id}/transcript`.
///
/// Each entry in `assignments` sets (or clears, when `custom_speaker` is
/// `None`) the `custom_speaker` override for every transcript row in the
/// call whose `diarized_speaker_id` matches. Diarized speakers not listed
/// are left untouched. Empty `assignments` is a 204 no-op.
#[derive(Debug, Clone, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct EditCallTranscriptRequest {
    /// The set of per-diarized-speaker overrides to apply.
    pub assignments: Vec<CustomSpeakerAssignment>,
}

/// A transcript segment as returned in a [`CallRecord`].
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallRecordTranscriptSegment {
    /// Stable DB-row id for the segment.
    pub transcript_id: Uuid,
    /// LiveKit segment ID (nullable for archived records).
    pub segment_id: Option<String>,
    /// The speaker's user ID.
    pub speaker_id: String,
    /// Stable per-speaker identifier produced by the STT provider's diarization
    /// pass. Unique across tracks in the call. `None` when the provider didn't
    /// return a speaker label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub diarized_speaker_id: Option<String>,
    /// The transcribed text content.
    pub content: String,
    /// When the speaker started this segment.
    pub started_at: DateTime<Utc>,
    /// When the speaker stopped (if known).
    pub ended_at: Option<DateTime<Utc>>,
    /// Ordering within the call.
    pub sequence_num: i32,
}

/// A participant as returned in a [`CallRecord`] (historic — includes `left_at`).
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallRecordParticipant {
    /// The Macro user id.
    pub user_id: String,
    /// When the user joined the call.
    pub joined_at: DateTime<Utc>,
    /// When the user left (None if still in an active call).
    pub left_at: Option<DateTime<Utc>>,
}

/// A non-account guest as returned in a [`CallRecord`].
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallRecordGuest {
    /// Opaque guest identity; matches the guest's transcript `speaker_id`.
    pub id: super::meetings::GuestId,
    /// Guest-provided display name.
    pub display_name: String,
    /// When the guest joined the call.
    pub joined_at: DateTime<Utc>,
    /// When the guest left (None if still in an active call).
    pub left_at: Option<DateTime<Utc>>,
}

/// Full record of a call, unifying rows from `calls` (active) and
/// `call_records` (archived) into a single response shape.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallRecord {
    /// The call identifier.
    pub call_id: Uuid,
    /// The channel this call belongs to.
    pub channel_id: Option<Uuid>,
    /// Where this call's discussion lives.
    pub discussion: CallDiscussion,
    /// The RTC room name. `None` for imported calls, which never had a room.
    pub room_name: Option<String>,
    /// User who created the call.
    pub created_by: String,
    /// When the call started (created_at for active, started_at for archived).
    pub started_at: DateTime<Utc>,
    /// When the call ended (None if still active).
    pub ended_at: Option<DateTime<Utc>>,
    /// Call duration in milliseconds (None if still active).
    pub duration_ms: Option<i64>,
    /// Recording egress ID, if any.
    pub egress_id: Option<String>,
    /// When the egress recording actually began. `None` until the
    /// `egress_started` webhook arrives (typically a few seconds after
    /// `started_at`). Frontend should anchor transcript-to-audio sync to
    /// this value when present, falling back to `started_at` otherwise.
    pub recording_started_at: Option<DateTime<Utc>>,
    /// S3 object key for the call recording (internal, not serialized).
    #[serde(skip_serializing)]
    pub recording_key: Option<String>,
    /// Stored S3 object key/path for the preview image (internal, not serialized).
    #[serde(skip_serializing)]
    pub preview_key: Option<String>,
    /// Presigned URL for the call recording, if available.
    pub recording_url: Option<String>,
    /// Presigned URL for the call recording preview image, if available.
    pub recording_preview_url: Option<String>,
    /// Resolved display name for the channel.
    pub channel_name: Option<String>,
    /// User-supplied or AI-generated display name for the call. Only set on
    /// archived `call_records`; active calls always return `None`.
    pub custom_name: Option<String>,
    /// AI-generated summary of the call. Only set on archived `call_records`
    /// once summarization has run; active calls always return `None`.
    pub summary: Option<String>,
    /// The canonical access level granted to the creator's team, or `None`
    /// when the call is not shared with the team. Calls only ever grant
    /// `View`, and only once archived: while the call is live this is `None`
    /// and `share_with_team` carries the pending toggle.
    pub team_share_access_level: Option<AccessLevel>,
    /// Whether the call is shared with the creator's team. While the call is
    /// live this is the pending toggle applied at archive; afterwards it
    /// mirrors `team_share_access_level`.
    pub share_with_team: bool,
    /// Whether the call is currently active (from `calls` table).
    pub is_active: bool,
    /// Viewer-relative call status when fetched in the context of a specific user.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<CallStatus>,
    /// The caller's effective access level on this call. Set only on the
    /// single-record read; `None` in list contexts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_access_level: Option<AccessLevel>,
    /// Whether the authenticated viewer has declined this call on any device.
    /// Set on the single-record read so clients that missed `call_declined`
    /// can still stop ringing via reconciliation; `false` in list contexts.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub viewer_has_declined: bool,
    /// Macro-account participants (both active and historic).
    pub participants: Vec<CallRecordParticipant>,
    /// Non-account guests (both active and historic). Guests only ever exist
    /// on standalone meeting calls, never on channel calls.
    pub guests: Vec<CallRecordGuest>,
    /// Transcript segments ordered by `sequence_num`.
    pub transcript: Vec<CallRecordTranscriptSegment>,
    /// External provenance for calls imported from another provider; `None`
    /// for calls recorded in Macro.
    pub source: Option<CallRecordSource>,
}

/// Where an imported call came from.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallRecordSource {
    /// Provider that supplied the call.
    pub provider: crate::domain::records::CallProvider,
    /// Link to the call in the provider's app, if it has one.
    pub external_url: Option<String>,
}

/// Storage object keys associated with a deleted archived call record.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeletedCallRecordStorageKeys {
    /// S3 object key for the MP4 recording, without the `calls/` prefix.
    pub recording_key: Option<String>,
    /// Stored S3 object key/path for the preview image.
    pub preview_key: Option<String>,
}

/// Lightweight preview of a call record, returned by the batch preview endpoint.
///
/// Each requested id resolves to one of two outcomes: the call exists
/// (`Exists`) or it does not (`DoesNotExist`). The endpoint does not perform
/// access checks, so there is no separate "not authorized" variant.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CallRecordPreview {
    /// The call exists (in either the active or archived table).
    Exists(CallRecordPreviewData),
    /// No call with this id exists in either the active or archived tables.
    DoesNotExist(WithCallId),
}

/// Wrapper carrying just a call id. Used by the [`CallRecordPreview::DoesNotExist`]
/// variant.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct WithCallId {
    /// The call identifier.
    pub call_id: Uuid,
}

/// Preview payload returned for each found call id.
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct CallRecordPreviewData {
    /// The call identifier.
    pub call_id: Uuid,
    /// The channel this call belongs to.
    pub channel_id: Option<Uuid>,
    /// Resolved display name for the channel.
    pub channel_name: Option<String>,
    /// User-supplied or AI-generated display name for the call. Only set on
    /// archived `call_records`; active calls always return `None`.
    pub custom_name: Option<String>,
    /// When the call started (created_at for active, started_at for archived).
    pub started_at: DateTime<Utc>,
    /// When the call ended (None if still active).
    pub ended_at: Option<DateTime<Utc>>,
}

/// Maximum number of call ids accepted in a single batch preview request.
///
/// Requests exceeding this limit are rejected with `400 Bad Request` so that
/// DB work and response size remain bounded per call.
pub const MAX_BATCH_CALL_IDS: usize = 100;

/// Request body for `POST /call/record/preview`.
///
/// The `call_ids` list is bounded at [`MAX_BATCH_CALL_IDS`]; the handler
/// rejects anything larger with a 400 before touching the database.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct GetBatchCallRecordPreviewRequest {
    /// The call ids to preview. Duplicate ids are deduplicated server-side.
    /// Capped at [`MAX_BATCH_CALL_IDS`] entries.
    pub call_ids: Vec<Uuid>,
}

/// Response body for `POST /call/record/preview`.
#[derive(Debug, serde::Serialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct GetBatchCallRecordPreviewResponse {
    /// One entry per deduplicated input id.
    pub previews: Vec<CallRecordPreview>,
}

/// Request to fetch recent call records for a user (used by Soup).
#[derive(Debug)]
pub struct GetCallRecordsRequest {
    /// The user whose call records to fetch.
    pub user_id: MacroUserIdStr<'static>,
    /// Maximum number of records to return.
    pub limit: u32,
    /// Sort or cursor-based pagination query with optional filter.
    pub query: Query<Uuid, SimpleSortMethod, LiteralTree<CallLiteral>>,
}

/// The order and keyset position of one page of a user's call records.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CallRecordPage {
    /// Order by start time; otherwise by last activity (end time, or start
    /// time for a call that has not ended), the way Soup sorts calls.
    pub by_start: bool,
    /// Resume strictly after this sort timestamp and call id.
    pub after: Option<(DateTime<Utc>, Uuid)>,
}

impl CallRecordPage {
    /// The page a Soup query asks for.
    pub fn from_query<F>(query: &Query<Uuid, SimpleSortMethod, F>) -> Self {
        let by_start = matches!(query.sort_method(), SimpleSortMethod::CreatedAt);
        let after = match query {
            Query::Sort(..) => None,
            Query::Cursor(cursor) => Some((cursor.val.last_val, cursor.id)),
        };
        Self { by_start, after }
    }
}

/// Errors that can occur when adding a participant to a call at the
/// repository boundary. Splitting the "already-active-elsewhere" case into
/// a typed variant lets the service handle it without looking at the
/// underlying database error type.
#[derive(Debug, thiserror::Error)]
pub enum AddParticipantError {
    /// The user is already an active participant in another call, as
    /// enforced by the DB-level partial unique index on
    /// `call_participants (user_id) WHERE left_at IS NULL`.
    #[error("user is already an active participant in another call")]
    UserAlreadyActive,
    /// Any other repository/infrastructure error.
    #[error(transparent)]
    Repository(anyhow::Error),
}

/// Errors that can occur during call operations.
#[derive(Debug, thiserror::Error)]
pub enum CallError {
    /// No active call found for this channel.
    #[error("no active call found for channel {0}")]
    NotFound(String),
    /// The call existed, but has already ended.
    #[error("call has ended")]
    Ended,
    /// The caller is already participating in a different call.
    #[error("user is in another call")]
    InOtherCall,
    /// This RTC identity is already connected to the room.
    #[error("identity is already connected")]
    AlreadyConnected,
    /// A per-caller start budget has been exhausted.
    #[error("call start rate limit exceeded")]
    RateLimited,
    /// User is not in the call.
    #[error("user not in call")]
    NotInCall,
    /// User is already an active participant in another call. The inner
    /// string is the `channel_id` of that other call, so clients can show
    /// a targeted message (and optionally deep-link to leave it).
    #[error("user is already in a call in channel {0}")]
    AlreadyInCall(String),
    /// Authentication or signature validation failed.
    #[error("authentication failed")]
    Auth,
    /// The request body violates an API contract (e.g. exceeds a size cap).
    #[error("{0}")]
    InvalidRequest(String),
    /// The caller is authenticated but not allowed to perform this change
    /// (for example, only the call's creator may change team sharing).
    #[error("forbidden: {0}")]
    Forbidden(String),
    /// The requested change conflicts with the persisted state (for example a
    /// stale team-share revision); the caller should reload and retry.
    #[error("conflict: {0}")]
    Conflict(String),
    /// An internal error occurred.
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

impl From<TeamSharePolicyError> for CallError {
    fn from(error: TeamSharePolicyError) -> Self {
        match error {
            TeamSharePolicyError::MissingActor | TeamSharePolicyError::NotOwner => {
                Self::Forbidden(error.to_string())
            }
            TeamSharePolicyError::InvalidRevision => Self::Conflict(error.to_string()),
            TeamSharePolicyError::MissingTeam
            | TeamSharePolicyError::InvalidLevel
            | TeamSharePolicyError::ContradictoryInputs => Self::InvalidRequest(error.to_string()),
        }
    }
}

/// Team memory may only include calls associated with a channel.
/// Standalone invitations and their records always keep team sharing disabled.
#[cfg(feature = "ports")]
pub(crate) fn permitted_team_memory_intent(channel_id: Option<Uuid>, enabled: bool) -> bool {
    channel_id.is_some() && enabled
}