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.

124 KB
Raw Blame
use std::{ops::Deref, sync::Arc, sync::LazyLock};

use crate::domain::meetings::GuestId;
use crate::domain::models::{
    AddParticipantError, CallRecord, CallRecordPage, CallRecordPreview, CustomSpeakerAssignment,
    EditCallRecordRepoArgs, TranscriptSegmentRequest,
};
use crate::domain::ports::CallRepository;
use crate::outbound::pg_call_repo::PgCallRepo;
use chrono::{Duration, SubsecRound, Utc};
use filter_ast::Expr;
use item_filters::{
    CallStatus,
    ast::{LiteralTree, call::CallLiteral},
};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::channel_share_permission::{
    UpdateChannelSharePermission, UpdateOperation,
};
use models_permissions::share_permission::{LinkShare, UpdateSharePermissionRequestV2};
use sqlx::{Pool, Postgres};
use uuid::Uuid;

fn attended_filter(b: bool) -> LiteralTree<CallLiteral> {
    Some(Arc::new(Expr::Literal(CallLiteral::Attended(b))))
}

fn status_filter(status: CallStatus) -> LiteralTree<CallLiteral> {
    Some(Arc::new(Expr::Literal(CallLiteral::Status(status))))
}

fn tag_property_literal(option_id: Uuid) -> CallLiteral {
    use item_filters::ast::properties::{PropertiesLiteral, PropertyMatchValue};
    CallLiteral::Property(PropertiesLiteral {
        property_definition_id: Uuid::from_u128(0xdef),
        entity_type: None,
        value: PropertyMatchValue::SelectOption(option_id),
    })
}

fn not_status_filter(status: CallStatus) -> LiteralTree<CallLiteral> {
    let expr = Expr::Literal(CallLiteral::Status(status));
    Some(Arc::new(Expr::is_not(expr)))
}

fn call_ids_filter(ids: &[Uuid]) -> LiteralTree<CallLiteral> {
    let mut iter = ids.iter().copied().map(CallLiteral::CallId);
    let first = iter.next()?;
    let expr = iter.fold(Expr::Literal(first), |acc, lit| {
        Expr::Or(Box::new(acc), Box::new(Expr::Literal(lit)))
    });
    Some(Arc::new(expr))
}

pub(super) const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);
pub(super) const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);
pub(super) const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
const CALL2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca220);
const LATEST_FIRST: CallRecordPage = CallRecordPage {
    by_start: false,
    after: None,
};
pub(super) const CALL_ARCHIVED: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca2ed);
const MACRO_USER_A: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaa1);
const MACRO_USER_B: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbb2);
const MACRO_USER_C: Uuid = Uuid::from_u128(0xcccccccc_cccc_cccc_cccc_ccccccccccc3);
pub(super) static USER_A: LazyLock<MacroUserIdStr<'static>> =
    LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
pub(super) static USER_B: LazyLock<MacroUserIdStr<'static>> =
    LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
static USER_C: LazyLock<MacroUserIdStr<'static>> =
    LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
static USER_D: LazyLock<MacroUserIdStr<'static>> =
    LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());

pub(super) fn repo(pool: Pool<Postgres>) -> PgCallRepo {
    PgCallRepo::new(pool)
}

fn call_status(records: &[CallRecord], call_id: Uuid) -> Option<CallStatus> {
    records
        .iter()
        .find(|record| record.call_id == call_id)
        .and_then(|record| record.status)
}

fn assert_records_have_status(records: &[CallRecord], expected: CallStatus) {
    assert!(
        records.iter().all(|record| record.status == Some(expected)),
        "expected every record to have status {expected:?}: {records:#?}"
    );
}

fn axis_unit_vector(axis: usize) -> Vec<f32> {
    let mut v = vec![0.0_f32; 256];
    v[axis] = 1.0;
    v
}

async fn insert_voice(pool: &Pool<Postgres>, voice_id: Uuid, axis: usize) -> anyhow::Result<()> {
    sqlx::query("INSERT INTO voice (id, embedding) VALUES ($1, $2)")
        .bind(voice_id)
        .bind(pgvector::Vector::from(axis_unit_vector(axis)))
        .execute(pool)
        .await?;
    Ok(())
}

pub(super) async fn insert_user_mapping(
    pool: &Pool<Postgres>,
    user_id: &MacroUserIdStr<'_>,
    macro_user_id: Uuid,
) -> anyhow::Result<()> {
    sqlx::query(
        r#"
        INSERT INTO macro_user (id, username, email, stripe_customer_id)
        VALUES ($1, $2, $3, $4)
        ON CONFLICT (id) DO NOTHING
        "#,
    )
    .bind(macro_user_id)
    .bind(user_id.as_ref())
    .bind(user_id.email_str())
    .bind(format!("cus_{macro_user_id}"))
    .execute(pool)
    .await?;

    sqlx::query(
        r#"
        INSERT INTO "User" (id, email, "stripeCustomerId", macro_user_id)
        VALUES ($1, $2, $3, $4)
        ON CONFLICT (id) DO UPDATE SET macro_user_id = EXCLUDED.macro_user_id
        "#,
    )
    .bind(user_id.as_ref())
    .bind(user_id.email_str())
    .bind(format!("cus_{macro_user_id}"))
    .bind(macro_user_id)
    .execute(pool)
    .await?;

    Ok(())
}

// -- create_call --------------------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn a_calls_discussion_is_stored_with_it_and_outlives_archival(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let threaded = Uuid::now_v7();
    repo.create_call(&threaded, &CH2, "room-ch2", USER_B.deref().copied(), true)
        .await?
        .expect("should create new call");

    let live = repo.get_call_record_by_call_id(&threaded).await?.unwrap();
    assert_eq!(
        live.discussion,
        crate::domain::models::CallDiscussion::ChannelThread {
            channel_id: CH2,
            root_id: threaded,
        }
    );

    let archived = repo.archive_call(&threaded).await?;
    assert!(archived.channel_thread);
    let record = repo.get_call_record_by_call_id(&threaded).await?.unwrap();
    assert_eq!(record.discussion, live.discussion);

    let existing = repo
        .get_call_record_by_call_id(&CALL1)
        .await?
        .expect("the fixture call exists");
    assert_eq!(
        existing.discussion,
        crate::domain::models::CallDiscussion::CallChat { call_id: CALL1 }
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn create_call_returns_call(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let id = Uuid::now_v7();
    let call = repo
        .create_call(&id, &CH2, "room-ch2", USER_B.deref().copied(), false)
        .await?
        .expect("should create new call");

    assert_eq!(call.id, id);
    assert_eq!(call.channel_id, Some(CH2));
    assert_eq!(call.room_name, "room-ch2");
    assert_eq!(call.created_by, USER_B.as_ref());

    let share_permission_id =
        sqlx::query_scalar!(r#"SELECT share_permission_id FROM calls WHERE id = $1"#, id,)
            .fetch_one(&pool)
            .await?;
    let permission = get_stored_share_permission(&pool, &share_permission_id).await?;
    assert_eq!(
        permission,
        StoredSharePermission {
            link_share: None,
            link_share_access_level: None,
        }
    );

    let channel_access_level = sqlx::query_scalar!(
        r#"
        SELECT csp.access_level::text AS "access_level!"
        FROM "ChannelSharePermission" csp
        WHERE csp.share_permission_id = $1 AND csp.channel_id = $2
        "#,
        share_permission_id,
        CH2.to_string(),
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(channel_access_level, "edit");
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn create_call_returns_none_on_duplicate_channel(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    // CH1 already has an active call from the fixture.
    let result = repo
        .create_call(
            &Uuid::now_v7(),
            &CH1,
            "room-dup",
            USER_A.deref().copied(),
            false,
        )
        .await?;

    assert!(result.is_none(), "should return None on conflict");
    Ok(())
}

// -- get_call_by_channel_id ---------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_by_channel_id_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    let call = repo.get_call_by_channel_id(&CH1).await?;

    let call = call.expect("call should exist for ch1");
    assert_eq!(call.id, CALL1);
    assert_eq!(call.channel_id, Some(CH1));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_by_channel_id_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    let call = repo.get_call_by_channel_id(&CH2).await?;

    assert!(call.is_none(), "ch2 has no active call");
    Ok(())
}

// -- get_call_by_room_name ----------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_by_room_name_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    let call = repo
        .get_call_by_room_name("00000000-0000-0000-0000-000000000c01")
        .await?;

    let call = call.expect("call should exist for room name");
    assert_eq!(call.id, CALL1);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_by_room_name_not_found(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    let call = repo.get_call_by_room_name("nonexistent-room").await?;

    assert!(call.is_none());
    Ok(())
}

// -- get_active_calls_for_user -------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_active_calls_for_user_returns_call_for_channel_member(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let calls = repo
        .get_active_calls_for_user(USER_C.deref().copied())
        .await?;

    assert_eq!(calls.len(), 1);
    assert_eq!(calls[0].call_id, CALL1);
    assert_eq!(calls[0].channel_id, CH1);
    assert_eq!(calls[0].created_by, USER_A.as_ref());
    assert_eq!(calls[0].participant_count, 2);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_active_calls_for_user_excludes_non_member_with_direct_call_access(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    // user-d has an entity_access row on call1 but is not a channel member.
    // Visibility is deliberately membership-based so it matches who receives
    // call_started/call_ended websocket events.
    let repo = repo(pool);
    let calls = repo
        .get_active_calls_for_user(USER_D.deref().copied())
        .await?;

    assert!(calls.is_empty());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_active_calls_for_user_excludes_zero_participant_calls(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    // A calls row with no active participants is an orphan (e.g. a dropped
    // RTC webhook) and must not surface as an active call.
    sqlx::query("UPDATE call_participants SET left_at = now() WHERE call_id = $1")
        .bind(CALL1)
        .execute(&pool)
        .await?;

    let repo = repo(pool);
    let calls = repo
        .get_active_calls_for_user(USER_C.deref().copied())
        .await?;

    assert!(calls.is_empty());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_active_calls_for_user_excludes_left_channel_members(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    sqlx::query(
        "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1 AND user_id = $2",
    )
    .bind(CH1)
    .bind(USER_C.deref().as_ref())
    .execute(&pool)
    .await?;

    let repo = repo(pool);
    let calls = repo
        .get_active_calls_for_user(USER_C.deref().copied())
        .await?;

    assert!(calls.is_empty());
    Ok(())
}

// -- add_participant / remove_participant / is_participant ---------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn add_and_check_participant(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);

    // user-c is not in the call yet.
    assert!(
        !repo
            .is_participant(&CALL1, &USER_C.deref().as_ref())
            .await?
    );

    let participant = repo
        .add_participant(&CALL1, USER_C.deref().copied())
        .await?;
    assert_eq!(participant.call_id, CALL1);
    assert_eq!(participant.user_id, USER_C.deref().as_ref());

    assert!(
        repo.is_participant(&CALL1, &USER_C.deref().as_ref())
            .await?
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn remove_participant_removes_from_db(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);

    assert!(repo.is_participant(&CALL1, &USER_B.as_ref()).await?);
    repo.remove_participant(&CALL1, USER_B.deref().copied())
        .await?;
    assert!(!repo.is_participant(&CALL1, &USER_B.as_ref()).await?);
    Ok(())
}

// -- record_decline / has_declined ----------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn record_decline_is_idempotent_and_scoped_to_the_user(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    assert!(!repo.has_declined(&CALL1, &USER_C.as_ref()).await?);

    repo.record_decline(&CALL1, USER_C.deref().copied()).await?;
    repo.record_decline(&CALL1, USER_C.deref().copied()).await?;

    assert!(repo.has_declined(&CALL1, &USER_C.as_ref()).await?);
    assert!(!repo.has_declined(&CALL1, &USER_B.as_ref()).await?);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn declines_are_dropped_with_the_call(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    repo.record_decline(&CALL1, USER_C.deref().copied()).await?;
    repo.delete_call(&CALL1).await?;

    let remaining: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM call_declines WHERE call_id = $1")
            .bind(CALL1)
            .fetch_one(&pool)
            .await?;
    assert_eq!(remaining, 0);
    Ok(())
}

// -- find_active_call_for_user ------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn find_active_call_for_user_returns_current_participation(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // user-a is an active participant in call1 (ch1) per the fixture.
    let found = repo
        .find_active_call_for_user(USER_A.deref().copied())
        .await?;
    assert_eq!(found, Some((CALL1, Some(CH1))));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn find_active_call_for_user_returns_none_when_never_joined(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // user-c is a channel member but not a participant in any call.
    let found = repo
        .find_active_call_for_user(USER_C.deref().copied())
        .await?;
    assert!(found.is_none());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn find_active_call_for_user_returns_none_after_leave(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    repo.remove_participant(&CALL1, USER_B.deref().copied())
        .await?;

    let found = repo
        .find_active_call_for_user(USER_B.deref().copied())
        .await?;
    assert!(found.is_none());
    Ok(())
}

// -- one-active-call-per-user invariant ---------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn add_participant_rejects_user_already_active_in_other_call(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // Seed a second active call in ch2 (the fixture leaves ch2 empty).
    repo.create_call(&CALL2, &CH2, "room-ch2", USER_C.deref().copied(), false)
        .await?
        .expect("should create call2 in ch2");

    // user-a is already active in call1 (ch1) per the fixture. Trying to
    // add them to call2 (ch2) must hit the partial unique index and surface
    // as AddParticipantError::UserAlreadyActive.
    let err = repo
        .add_participant(&CALL2, USER_A.deref().copied())
        .await
        .expect_err("should reject user already active elsewhere");

    assert!(
        matches!(err, AddParticipantError::UserAlreadyActive),
        "expected UserAlreadyActive, got {err:?}"
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn add_participant_same_call_rejoin_is_idempotent(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // user-a is already active in call1. Re-adding to the same call must
    // succeed (upsert no-op) — the partial unique index only rejects when
    // the active row would be in a *different* call.
    let participant = repo
        .add_participant(&CALL1, USER_A.deref().copied())
        .await?;
    assert_eq!(participant.call_id, CALL1);
    assert_eq!(participant.user_id, USER_A.as_ref());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn add_participant_allows_join_other_call_after_leave(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    repo.create_call(&CALL2, &CH2, "room-ch2", USER_C.deref().copied(), false)
        .await?
        .expect("should create call2 in ch2");

    // user-a leaves call1, freeing them up to join call2.
    repo.remove_participant(&CALL1, USER_A.deref().copied())
        .await?;

    let participant = repo
        .add_participant(&CALL2, USER_A.deref().copied())
        .await?;
    assert_eq!(participant.call_id, CALL2);
    assert_eq!(participant.user_id, USER_A.as_ref());
    Ok(())
}

// -- get_participants ---------------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_participants_returns_all(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    let participants = repo.get_participants(&CALL1).await?;

    assert_eq!(participants.len(), 2);
    let user_ids: Vec<&str> = participants.iter().map(|p| p.user_id.as_str()).collect();
    assert!(user_ids.contains(&USER_A.as_ref()));
    assert!(user_ids.contains(&USER_B.as_ref()));
    Ok(())
}

// -- get_participant_count ----------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_participant_count_correct(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);

    assert_eq!(repo.get_participant_count(&CALL1).await?, 2);

    repo.remove_participant(&CALL1, USER_B.deref().copied())
        .await?;
    assert_eq!(repo.get_participant_count(&CALL1).await?, 1);
    Ok(())
}

// -- delete_call --------------------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn delete_call_cascades_to_participants(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    repo.delete_call(&CALL1).await?;

    assert!(repo.get_call_by_channel_id(&CH1).await?.is_none());
    // Participants should be cascade-deleted.
    assert_eq!(repo.get_participant_count(&CALL1).await?, 0);
    // entity_access grants for the call must be cleaned up atomically.
    let remaining_grants: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM entity_access WHERE entity_id = $1 AND entity_type = 'call'"#,
        CALL1,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(remaining_grants, 0);
    Ok(())
}

// -- archive_call -------------------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn archive_call_creates_record_and_deletes_ephemeral(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    repo.set_egress_id(&CALL1, "egress-archive-test").await?;

    let archived = repo.archive_call(&CALL1).await?;

    // Ephemeral call should be gone.
    assert!(repo.get_call_by_channel_id(&CH1).await?.is_none());
    assert_eq!(repo.get_participant_count(&CALL1).await?, 0);

    // call_records should have the archived call.
    let record = sqlx::query!(
        r#"
        SELECT id, channel_id, room_name, created_by, started_at, ended_at, duration_ms
        FROM call_records
        WHERE id = $1
        "#,
        archived.call_id,
    )
    .fetch_one(&pool)
    .await?;

    assert_eq!(archived.call_id, CALL1);
    assert_eq!(archived.channel_id, Some(CH1));
    assert_eq!(archived.created_by, USER_A.as_ref());
    assert_eq!(archived.started_at, record.started_at);
    assert_eq!(archived.ended_at, record.ended_at);
    assert_eq!(archived.duration_ms, record.duration_ms);
    assert!(archived.has_recording);
    assert_eq!(archived.participants.len(), 2);

    assert_eq!(record.channel_id, archived.channel_id);
    assert_eq!(record.created_by, archived.created_by);
    assert!(record.duration_ms >= 0);
    assert!(record.ended_at >= record.started_at);

    // call_record_participants should have both participants.
    let participants = sqlx::query_scalar!(
        r#"
        SELECT user_id
        FROM call_record_participants
        WHERE call_record_id = $1
        ORDER BY joined_at ASC
        "#,
        archived.call_id,
    )
    .fetch_all(&pool)
    .await?;

    let mut returned = archived.participants.clone();
    returned.sort();
    let mut stored = participants.clone();
    stored.sort();
    assert_eq!(returned, stored);
    assert!(participants.contains(&USER_A.to_string()));
    assert!(participants.contains(&USER_B.to_string()));
    Ok(())
}

// -- archive preserves soft-deleted participants ------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn archive_call_preserves_soft_deleted_participants(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    // Soft-delete both participants (simulates leave_or_end_call flow).
    repo.remove_participant(&CALL1, USER_A.deref().copied())
        .await?;
    repo.remove_participant(&CALL1, USER_B.deref().copied())
        .await?;

    // Active count should be 0 but rows still exist.
    assert_eq!(repo.get_participant_count(&CALL1).await?, 0);

    // Archive the call.
    let archived = repo.archive_call(&CALL1).await?;
    assert_eq!(archived.participants.len(), 2);
    assert!(archived.participants.contains(&USER_A.to_string()));
    assert!(archived.participants.contains(&USER_B.to_string()));
    assert!(!archived.has_recording);

    // call_record_participants should have both participants with left_at set.
    let rows = sqlx::query!(
        r#"
        SELECT user_id, left_at
        FROM call_record_participants
        WHERE call_record_id = $1
        ORDER BY joined_at ASC
        "#,
        archived.call_id,
    )
    .fetch_all(&pool)
    .await?;

    assert_eq!(rows.len(), archived.participants.len());
    let user_ids: Vec<&str> = rows.iter().map(|r| r.user_id.as_str()).collect();
    assert!(user_ids.contains(&USER_A.as_ref()));
    assert!(user_ids.contains(&USER_B.as_ref()));
    // Both should have left_at set since they were soft-deleted.
    assert!(rows.iter().all(|r| r.left_at.is_some()));

    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn archive_call_returns_no_result_when_call_is_missing(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    assert!(repo.archive_call(&CALL2).await.is_err());
    assert!(repo.get_call_record_by_call_id(&CALL2).await?.is_none());

    Ok(())
}

/// Test helper: give `user_id` a brand new team owned by that user. Inserts
/// the parent `macro_user` and `User` rows that the `team_user` FK requires.
pub(super) async fn give_user_a_team(
    pool: &Pool<Postgres>,
    user_id: &str,
    team_id: &Uuid,
) -> anyhow::Result<()> {
    let macro_user_id = Uuid::now_v7();

    sqlx::query(
        r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $3, '')"#,
    )
    .bind(macro_user_id)
    .bind(user_id)
    .bind(format!("{user_id}@test.com"))
    .execute(pool)
    .await?;

    sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $2, $3)"#)
        .bind(user_id)
        .bind(format!("{user_id}@test.com"))
        .bind(macro_user_id)
        .execute(pool)
        .await?;

    sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)
        .bind(team_id)
        .bind("test team")
        .bind(user_id)
        .execute(pool)
        .await?;

    sqlx::query(r#"INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'owner')"#)
        .bind(user_id)
        .bind(team_id)
        .execute(pool)
        .await?;

    Ok(())
}

pub(super) async fn team_entity_access_count(
    pool: &Pool<Postgres>,
    call_id: Uuid,
) -> anyhow::Result<i64> {
    Ok(sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM entity_access WHERE entity_id = $1 AND source_type = 'team'"#,
        call_id,
    )
    .fetch_one(pool)
    .await?)
}

// Team sharing across archive is covered in `team_share/test.rs`: archive
// neither grants nor revokes anything; canonical state simply carries over.

// -- archive_call preserves id and share_permission_id ------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn archive_call_preserves_id_and_share_permission(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    // Read the share_permission_id from the active call before archiving.
    let active_share_permission_id = sqlx::query_scalar!(
        r#"SELECT share_permission_id FROM calls WHERE id = $1"#,
        CALL1,
    )
    .fetch_one(&pool)
    .await?;

    let archived = repo.archive_call(&CALL1).await?;

    // The call_record id should be the same as the original call id.
    assert_eq!(archived.call_id, CALL1);

    // The share_permission_id should carry over to the call_record.
    let record_share_permission_id = sqlx::query_scalar!(
        r#"SELECT share_permission_id FROM call_records WHERE id = $1"#,
        archived.call_id,
    )
    .fetch_one(&pool)
    .await?;

    assert_eq!(record_share_permission_id, active_share_permission_id);

    Ok(())
}

// -- get_call_record_by_egress_id --------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_by_egress_id_returns_call_and_channel_context(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let context = repo.get_call_record_by_egress_id("egress-arch-1").await?;

    assert_eq!(context, Some((CALL_ARCHIVED, Some(CH1))));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_by_egress_id_returns_none_for_unknown_id(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let context = repo
        .get_call_record_by_egress_id("unknown-egress-id")
        .await?;

    assert_eq!(context, None);
    Ok(())
}

// -- set_active_call_recording_key --------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn set_active_call_recording_key_updates_matching_call(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    // Set egress_id on the fixture call first.
    repo.set_egress_id(&CALL1, "egress-123").await?;

    let recording_key = "0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4";
    let preview_key = "calls/0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832/PREVIEW.jpg";

    // Should update and return true.
    let updated = repo
        .set_active_call_recording_key("egress-123", recording_key)
        .await?;
    assert!(updated);

    sqlx::query!(
        r#"UPDATE calls SET preview_url = $2 WHERE id = $1"#,
        CALL1,
        preview_key,
    )
    .execute(&pool)
    .await?;

    // Verify the key is on the active call.
    let call = repo.get_call_by_channel_id(&CH1).await?.unwrap();
    assert_eq!(call.egress_id.as_deref(), Some("egress-123"));

    // Now archive and verify recording_key and preview key carry forward.
    let archived = repo.archive_call(&CALL1).await?;
    let recording = sqlx::query!(
        r#"SELECT recording_key, preview_url FROM call_records WHERE id = $1"#,
        archived.call_id,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(recording.recording_key.as_deref(), Some(recording_key));
    assert_eq!(recording.preview_url.as_deref(), Some(preview_key));

    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn set_active_call_recording_key_returns_false_when_no_match(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let updated = repo
        .set_active_call_recording_key(
            "nonexistent-egress",
            "0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4",
        )
        .await?;
    assert!(!updated);

    Ok(())
}

// -- create_transcript_segment ------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn create_transcript_segment_stores_and_increments_sequence(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let now = Utc::now();

    let seg1 = TranscriptSegmentRequest {
        segment_id: "seg-001".to_string(),
        speaker_id: USER_A.to_string(),
        diarized_speaker_id: Some("spk-a0".to_string()),
        content: "hello world".to_string(),
        started_at: now,
        ended_at: Some(now),
        is_final: true,
        stream_started_at: None,
        embedding: None,
    };
    let seg2 = TranscriptSegmentRequest {
        segment_id: "seg-002".to_string(),
        speaker_id: USER_B.to_string(),
        diarized_speaker_id: None,
        content: "hi there".to_string(),
        started_at: now,
        ended_at: Some(now),
        is_final: true,
        stream_started_at: None,
        embedding: None,
    };

    repo.create_transcript_segment(&CALL1, &seg1, None).await?;
    repo.create_transcript_segment(&CALL1, &seg2, None).await?;

    // Duplicate segment_id should be ignored.
    repo.create_transcript_segment(&CALL1, &seg1, None).await?;

    let rows = sqlx::query!(
        r#"
        SELECT speaker_id, diarized_speaker_id, content, sequence_num
        FROM call_transcripts
        WHERE call_id = $1
        ORDER BY sequence_num ASC
        "#,
        CALL1,
    )
    .fetch_all(&pool)
    .await?;

    assert_eq!(rows.len(), 2);
    assert_eq!(rows[0].content, "hello world");
    assert_eq!(rows[0].sequence_num, 1);
    assert_eq!(rows[0].diarized_speaker_id.as_deref(), Some("spk-a0"));
    assert_eq!(rows[1].content, "hi there");
    assert_eq!(rows[1].sequence_num, 2);
    assert_eq!(rows[1].diarized_speaker_id, None);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_transcript_voice_id_for_speaker_uses_diarized_speaker_id(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let now = Utc::now();
    let voice_a = macro_uuid::generate_uuid_v7();
    let voice_b = macro_uuid::generate_uuid_v7();
    insert_voice(&pool, voice_a, 0).await?;
    insert_voice(&pool, voice_b, 1).await?;

    let seg_a = TranscriptSegmentRequest {
        segment_id: "seg-voice-a".to_string(),
        speaker_id: USER_A.to_string(),
        diarized_speaker_id: Some("spk-a0".to_string()),
        content: "first voice".to_string(),
        started_at: now,
        ended_at: Some(now),
        is_final: true,
        stream_started_at: None,
        embedding: None,
    };
    let seg_b = TranscriptSegmentRequest {
        segment_id: "seg-voice-b".to_string(),
        speaker_id: USER_A.to_string(),
        diarized_speaker_id: Some("spk-a1".to_string()),
        content: "second voice".to_string(),
        started_at: now,
        ended_at: Some(now),
        is_final: true,
        stream_started_at: None,
        embedding: None,
    };

    repo.create_transcript_segment(&CALL1, &seg_a, Some(voice_a))
        .await?;
    repo.create_transcript_segment(&CALL1, &seg_b, Some(voice_b))
        .await?;

    assert_eq!(
        repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), Some("spk-a0"))
            .await?,
        Some(voice_a)
    );
    assert_eq!(
        repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), Some("spk-a1"))
            .await?,
        Some(voice_b)
    );
    assert_eq!(
        repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), Some("missing"))
            .await?,
        None
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_transcript_voice_id_for_speaker_falls_back_to_participant_id(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let now = Utc::now();
    let voice_id = macro_uuid::generate_uuid_v7();
    insert_voice(&pool, voice_id, 0).await?;

    let segment = TranscriptSegmentRequest {
        segment_id: "seg-voice-participant".to_string(),
        speaker_id: USER_A.to_string(),
        diarized_speaker_id: None,
        content: "voice without diarization".to_string(),
        started_at: now,
        ended_at: Some(now),
        is_final: true,
        stream_started_at: None,
        embedding: None,
    };

    repo.create_transcript_segment(&CALL1, &segment, Some(voice_id))
        .await?;

    assert_eq!(
        repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), None)
            .await?,
        Some(voice_id)
    );
    assert_eq!(
        repo.get_transcript_voice_id_for_speaker(&CALL1, USER_B.as_ref(), None)
            .await?,
        None
    );
    Ok(())
}

// -- archive_call copies transcripts ------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let now = Utc::now();

    // Add a transcript segment to the active call.
    let seg = TranscriptSegmentRequest {
        segment_id: "seg-archive-001".to_string(),
        speaker_id: USER_A.to_string(),
        diarized_speaker_id: Some("spk-archive-a0".to_string()),
        content: "test transcript".to_string(),
        started_at: now,
        ended_at: Some(now),
        is_final: true,
        stream_started_at: None,
        embedding: None,
    };
    repo.create_transcript_segment(&CALL1, &seg, None).await?;

    // Archive the call.
    let archived = repo.archive_call(&CALL1).await?;

    // Transcripts should be in call_record_transcripts.
    let transcripts = sqlx::query!(
        r#"
        SELECT speaker_id, diarized_speaker_id, content, sequence_num
        FROM call_record_transcripts
        WHERE call_record_id = $1
        "#,
        archived.call_id,
    )
    .fetch_all(&pool)
    .await?;

    assert_eq!(transcripts.len(), 1);
    assert_eq!(transcripts[0].content, "test transcript");
    assert_eq!(transcripts[0].speaker_id, USER_A.as_ref());
    assert_eq!(
        transcripts[0].diarized_speaker_id.as_deref(),
        Some("spk-archive-a0")
    );
    assert_eq!(transcripts[0].sequence_num, 1);

    // Ephemeral transcripts should be gone (cascaded).
    let ephemeral = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM call_transcripts WHERE call_id = $1"#,
        CALL1,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(ephemeral, 0);

    Ok(())
}

// -- archive_call rolls up consecutive same-speaker transcripts --------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn archive_call_rolls_up_consecutive_same_speaker_transcripts(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    // Truncate to microseconds to match Postgres TIMESTAMPTZ precision,
    // otherwise the round-trip drops sub-microsecond nanoseconds and the
    // timestamp comparison below is flaky.
    let t0 = Utc::now().trunc_subsecs(6);

    // Row 1: USER_A / spk-a0, ends at t0+3s.
    // Row 2: USER_A / spk-a0, starts at t0+5s (gap=2s) -> merges with row 1.
    // Row 3: USER_A / spk-a0, starts at t0+20s (gap=12s) -> new group.
    // Row 4: USER_B / spk-b0 -> new group (different speaker).
    // Row 5: USER_B / spk-b1 -> new group (different diarized_speaker_id).
    let segs = [
        (
            "seg-1",
            USER_A.to_string(),
            Some("spk-a0"),
            "hello",
            t0,
            t0 + Duration::seconds(3),
        ),
        (
            "seg-2",
            USER_A.to_string(),
            Some("spk-a0"),
            "world",
            t0 + Duration::seconds(5),
            t0 + Duration::seconds(8),
        ),
        (
            "seg-3",
            USER_A.to_string(),
            Some("spk-a0"),
            "distant",
            t0 + Duration::seconds(20),
            t0 + Duration::seconds(22),
        ),
        (
            "seg-4",
            USER_B.to_string(),
            Some("spk-b0"),
            "hey",
            t0 + Duration::seconds(22),
            t0 + Duration::seconds(24),
        ),
        (
            "seg-5",
            USER_B.to_string(),
            Some("spk-b1"),
            "other",
            t0 + Duration::seconds(24),
            t0 + Duration::seconds(26),
        ),
    ];
    for (segment_id, speaker_id, diar, content, started_at, ended_at) in segs {
        repo.create_transcript_segment(
            &CALL1,
            &TranscriptSegmentRequest {
                segment_id: segment_id.to_string(),
                speaker_id,
                diarized_speaker_id: diar.map(str::to_string),
                content: content.to_string(),
                started_at,
                ended_at: Some(ended_at),
                is_final: true,
                stream_started_at: None,
                embedding: None,
            },
            None,
        )
        .await?;
    }

    let archived = repo.archive_call(&CALL1).await?;

    let rows = sqlx::query!(
        r#"
        SELECT speaker_id, diarized_speaker_id, content, started_at, ended_at
        FROM call_record_transcripts
        WHERE call_record_id = $1
        ORDER BY sequence_num ASC
        "#,
        archived.call_id,
    )
    .fetch_all(&pool)
    .await?;

    // 5 segments collapse into 4 rolled-up rows.
    assert_eq!(rows.len(), 4);

    // Group 1: seg-1 + seg-2 merged.
    assert_eq!(rows[0].speaker_id, USER_A.as_ref());
    assert_eq!(rows[0].diarized_speaker_id.as_deref(), Some("spk-a0"));
    assert_eq!(rows[0].content, "hello world");
    assert_eq!(rows[0].started_at, t0);
    assert_eq!(rows[0].ended_at, Some(t0 + Duration::seconds(8)));

    // Group 2: seg-3 alone (gap from seg-2 was 12s).
    assert_eq!(rows[1].speaker_id, USER_A.as_ref());
    assert_eq!(rows[1].diarized_speaker_id.as_deref(), Some("spk-a0"));
    assert_eq!(rows[1].content, "distant");

    // Group 3: seg-4 alone (different speaker_id).
    assert_eq!(rows[2].speaker_id, USER_B.as_ref());
    assert_eq!(rows[2].diarized_speaker_id.as_deref(), Some("spk-b0"));
    assert_eq!(rows[2].content, "hey");

    // Group 4: seg-5 alone (different diarized_speaker_id).
    assert_eq!(rows[3].speaker_id, USER_B.as_ref());
    assert_eq!(rows[3].diarized_speaker_id.as_deref(), Some("spk-b1"));
    assert_eq!(rows[3].content, "other");

    Ok(())
}

// -- get_stable_speaker_voices_for_call_record -------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_stable_speaker_voices_for_call_record_returns_all_voices_for_consistent_diarized_speakers(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let now = Utc::now();
    let voice_a = macro_uuid::generate_uuid_v7();
    let voice_b = macro_uuid::generate_uuid_v7();
    insert_voice(&pool, voice_a, 0).await?;
    insert_voice(&pool, voice_b, 1).await?;
    insert_user_mapping(&pool, USER_A.deref(), MACRO_USER_A).await?;
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;

    let segments = [
        // USER_A is stable: every row has the same non-null diarized speaker,
        // so all non-null voice ids from those rows should be returned.
        ("stable-a-1", USER_A.as_ref(), Some("spk-a0"), Some(voice_a)),
        ("stable-a-2", USER_A.as_ref(), Some("spk-a0"), Some(voice_b)),
        ("stable-a-3", USER_A.as_ref(), Some("spk-a0"), None),
        // USER_B is ambiguous: more than one distinct diarized speaker id.
        (
            "ambiguous-b-1",
            USER_B.as_ref(),
            Some("spk-b0"),
            Some(voice_a),
        ),
        (
            "ambiguous-b-2",
            USER_B.as_ref(),
            Some("spk-b1"),
            Some(voice_b),
        ),
        // USER_C is incomplete: at least one transcript row has no diarized speaker id.
        (
            "missing-c-1",
            USER_C.deref().as_ref(),
            Some("spk-c0"),
            Some(voice_a),
        ),
        ("missing-c-2", USER_C.deref().as_ref(), None, Some(voice_b)),
        // Unknown speaker ids are ignored even if their diarized speaker id is stable.
        (
            "unknown-speaker",
            "macro|[email protected]",
            Some("spk-unknown"),
            Some(voice_a),
        ),
    ];

    for (idx, (segment_id, speaker_id, diarized_speaker_id, voice_id)) in
        segments.into_iter().enumerate()
    {
        let started_at = now + Duration::seconds(idx as i64);
        repo.create_transcript_segment(
            &CALL1,
            &TranscriptSegmentRequest {
                segment_id: segment_id.to_string(),
                speaker_id: speaker_id.to_string(),
                diarized_speaker_id: diarized_speaker_id.map(str::to_string),
                content: segment_id.to_string(),
                started_at,
                ended_at: Some(started_at + Duration::milliseconds(100)),
                is_final: true,
                stream_started_at: None,
                embedding: None,
            },
            voice_id,
        )
        .await?;
    }

    let archived = repo.archive_call(&CALL1).await?;

    let mut stable = repo
        .get_stable_speaker_voices_for_call_record(&archived.call_id)
        .await?;
    stable.sort();

    let mut expected = vec![(MACRO_USER_A, voice_a), (MACRO_USER_A, voice_b)];
    expected.sort();
    assert_eq!(stable, expected);
    Ok(())
}

// -- get_call_record_by_call_id ----------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let now = Utc::now();

    // Ingest two transcript segments into the active call.
    repo.create_transcript_segment(
        &CALL1,
        &TranscriptSegmentRequest {
            segment_id: "seg-live-1".to_string(),
            speaker_id: USER_A.to_string(),
            diarized_speaker_id: Some("spk-live-a0".to_string()),
            content: "hello there".to_string(),
            started_at: now,
            ended_at: Some(now),
            is_final: true,
            stream_started_at: None,
            embedding: None,
        },
        None,
    )
    .await?;
    repo.create_transcript_segment(
        &CALL1,
        &TranscriptSegmentRequest {
            segment_id: "seg-live-2".to_string(),
            speaker_id: USER_B.to_string(),
            diarized_speaker_id: None,
            content: "general kenobi".to_string(),
            started_at: now,
            ended_at: Some(now),
            is_final: true,
            stream_started_at: None,
            embedding: None,
        },
        None,
    )
    .await?;

    let record = repo
        .get_call_record_by_call_id(&CALL1)
        .await?
        .expect("active call should be found");

    assert_eq!(record.call_id, CALL1);
    assert_eq!(record.channel_id, Some(CH1));
    assert!(record.is_active);
    // Live calls report the pending toggle (on by default); canonical state
    // is only written when the call is archived.
    assert_eq!(record.team_share_access_level, None);
    assert!(record.share_with_team);
    assert_eq!(record.status, None);
    assert!(record.ended_at.is_none());
    assert!(record.duration_ms.is_none());

    // Participants from fixture.
    let user_ids: Vec<&str> = record
        .participants
        .iter()
        .map(|p| p.user_id.as_str())
        .collect();
    assert_eq!(user_ids, vec![USER_A.as_ref(), USER_B.as_ref()]);

    // Transcripts ordered by sequence_num.
    assert_eq!(record.transcript.len(), 2);
    assert_eq!(record.transcript[0].sequence_num, 1);
    assert_eq!(record.transcript[0].content, "hello there");
    assert_eq!(
        record.transcript[0].segment_id.as_deref(),
        Some("seg-live-1")
    );
    assert_eq!(
        record.transcript[0].diarized_speaker_id.as_deref(),
        Some("spk-live-a0")
    );
    assert_eq!(record.transcript[1].sequence_num, 2);
    assert_eq!(record.transcript[1].content, "general kenobi");
    assert_eq!(record.transcript[1].diarized_speaker_id, None);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_returns_archived_call(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    let record = repo
        .get_call_record_by_call_id(&CALL_ARCHIVED)
        .await?
        .expect("archived call should be found");

    assert_eq!(record.call_id, CALL_ARCHIVED);
    assert_eq!(record.channel_id, Some(CH1));
    assert!(!record.is_active);
    assert_eq!(record.team_share_access_level, None);
    assert!(!record.share_with_team);
    assert_eq!(record.status, None);
    assert!(record.ended_at.is_some());
    assert_eq!(record.duration_ms, Some(300_000));
    assert_eq!(record.egress_id.as_deref(), Some("egress-arch-1"));

    // Participants from archived fixture (both have left_at).
    assert_eq!(record.participants.len(), 2);
    assert!(record.participants.iter().all(|p| p.left_at.is_some()));

    // Transcripts ordered by sequence_num.
    assert_eq!(record.transcript.len(), 3);
    assert_eq!(record.transcript[0].content, "archived hello");
    assert_eq!(
        record.transcript[0].diarized_speaker_id.as_deref(),
        Some("spk-arch-a0")
    );
    assert_eq!(record.transcript[1].content, "archived reply");
    assert_eq!(record.transcript[1].diarized_speaker_id, None);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_overrides_speaker_id_with_custom_speaker(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let record = repo
        .get_call_record_by_call_id(&CALL_ARCHIVED)
        .await?
        .expect("archived call should be found");

    // Row without an override returns the derived speaker_id.
    assert_eq!(record.transcript[0].content, "archived hello");
    assert_eq!(record.transcript[0].speaker_id, "macro|[email protected]");

    // Row with `custom_speaker` set returns the override, not the derived
    // speaker_id (which is `macro|[email protected]` in the fixture).
    assert_eq!(record.transcript[2].content, "archived overridden");
    assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");
    assert_eq!(
        record.transcript[2].diarized_speaker_id.as_deref(),
        Some("spk-arch-b0")
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_returns_none_for_unknown(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    let record = repo.get_call_record_by_call_id(&Uuid::now_v7()).await?;
    assert!(record.is_none());
    Ok(())
}

// -- batch_get_call_record_previews -------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn batch_get_call_record_previews_mixes_active_archived_and_missing(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let missing = Uuid::now_v7();

    let previews = repo
        .batch_get_call_record_previews(&[CALL1, CALL_ARCHIVED, missing], USER_A.deref().copied())
        .await?;

    assert_eq!(previews.len(), 3);

    // Active call comes back as Exists with ended_at = None.
    match &previews[0] {
        CallRecordPreview::Exists(data) => {
            assert_eq!(data.call_id, CALL1);
            assert_eq!(data.channel_id, Some(CH1));
            assert_eq!(data.channel_name.as_deref(), Some("call-test-channel"));
            assert!(data.ended_at.is_none());
        }
        other => panic!("expected Exists for active call, got {other:?}"),
    }

    // Archived call comes back as Exists with ended_at populated.
    match &previews[1] {
        CallRecordPreview::Exists(data) => {
            assert_eq!(data.call_id, CALL_ARCHIVED);
            assert_eq!(data.channel_id, Some(CH1));
            assert!(data.ended_at.is_some());
        }
        other => panic!("expected Exists for archived call, got {other:?}"),
    }

    // Missing id comes back as DoesNotExist.
    match &previews[2] {
        CallRecordPreview::DoesNotExist(w) => assert_eq!(w.call_id, missing),
        other => panic!("expected DoesNotExist for missing id, got {other:?}"),
    }

    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn batch_get_call_record_previews_deduplicates_input(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // Four inputs but only two distinct ids; response should have exactly two.
    let previews = repo
        .batch_get_call_record_previews(
            &[CALL1, CALL1, CALL_ARCHIVED, CALL1],
            USER_A.deref().copied(),
        )
        .await?;

    assert_eq!(previews.len(), 2, "duplicates should be collapsed");

    let ids: Vec<Uuid> = previews
        .iter()
        .map(|p| match p {
            CallRecordPreview::Exists(d) => d.call_id,
            CallRecordPreview::DoesNotExist(w) => w.call_id,
        })
        .collect();
    assert_eq!(
        ids,
        vec![CALL1, CALL_ARCHIVED],
        "first-occurrence order must be preserved"
    );
    Ok(())
}

#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn batch_get_call_record_previews_empty_input_returns_empty(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let previews = repo
        .batch_get_call_record_previews(&[], USER_A.deref().copied())
        .await?;
    assert!(previews.is_empty());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_seeks_past_the_soup_cursor(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let all = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;
    assert_eq!(all.len(), 2);

    // Each page resumes strictly after the previous page's last call, so a
    // feed never serves the same call twice and reaches every call.
    for by_start in [false, true] {
        let sort_ts = |record: &CallRecord| {
            if by_start {
                record.started_at
            } else {
                record.ended_at.unwrap_or(record.started_at)
            }
        };
        let mut seen = Vec::new();
        let mut page = CallRecordPage {
            by_start,
            after: None,
        };
        loop {
            let records = repo
                .get_call_records_by_user(USER_C.deref().copied(), 1, &None, page)
                .await?;
            let Some(last) = records.last() else { break };
            seen.push(last.call_id);
            page.after = Some((sort_ts(last), last.call_id));
            assert!(seen.len() <= all.len(), "a call repeated: {seen:?}");
        }
        let mut expected: Vec<_> = all.iter().map(|record| record.call_id).collect();
        expected.sort();
        seen.sort();
        assert_eq!(seen, expected);
    }
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_includes_channel_member_not_in_call(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // user-c is a member of CH1 (fixture) but is NOT in call_participants
    // for CALL1 or call_record_participants for CALL_ARCHIVED. Visibility
    // should now come from channel membership, so both calls should appear.
    let records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;

    assert_eq!(
        records.len(),
        2,
        "expected active + archived call for channel member"
    );
    assert!(records.iter().any(|r| r.call_id == CALL1 && r.is_active));
    assert!(
        records
            .iter()
            .any(|r| r.call_id == CALL_ARCHIVED && !r.is_active)
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_status_attended_for_participant(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;

    assert_eq!(records.len(), 2);
    assert_eq!(call_status(&records, CALL1), Some(CallStatus::Attended));
    assert_eq!(
        call_status(&records, CALL_ARCHIVED),
        Some(CallStatus::Attended)
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_status_missed_for_channel_nonparticipant(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;

    assert_eq!(records.len(), 2);
    assert_eq!(call_status(&records, CALL1), Some(CallStatus::Missed));
    assert_eq!(
        call_status(&records, CALL_ARCHIVED),
        Some(CallStatus::Missed)
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_status_unattended_for_accessible_non_channel_nonparticipant(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let records = repo
        .get_call_records_by_user(USER_D.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;

    assert_eq!(records.len(), 2);
    assert_eq!(call_status(&records, CALL1), Some(CallStatus::Unattended));
    assert_eq!(
        call_status(&records, CALL_ARCHIVED),
        Some(CallStatus::Unattended)
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_status_filters_return_exact_matches(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let attended = status_filter(CallStatus::Attended);
    let attended_records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &attended, LATEST_FIRST)
        .await?;
    assert_eq!(attended_records.len(), 2);
    assert_records_have_status(&attended_records, CallStatus::Attended);

    let missed = status_filter(CallStatus::Missed);
    let missed_records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &missed, LATEST_FIRST)
        .await?;
    assert_eq!(missed_records.len(), 2);
    assert_records_have_status(&missed_records, CallStatus::Missed);

    let unattended = status_filter(CallStatus::Unattended);
    let unattended_records = repo
        .get_call_records_by_user(USER_D.deref().copied(), 10, &unattended, LATEST_FIRST)
        .await?;
    assert_eq!(unattended_records.len(), 2);
    assert_records_have_status(&unattended_records, CallStatus::Unattended);

    let no_unattended_for_channel_member = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &unattended, LATEST_FIRST)
        .await?;
    assert!(no_unattended_for_channel_member.is_empty());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_status_legacy_attended_false_returns_not_participant_statuses(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let filter = attended_filter(false);

    let missed_records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(missed_records.len(), 2);
    assert_records_have_status(&missed_records, CallStatus::Missed);

    let unattended_records = repo
        .get_call_records_by_user(USER_D.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(unattended_records.len(), 2);
    assert_records_have_status(&unattended_records, CallStatus::Unattended);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_status_not_filter_complements_status(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let not_attended = not_status_filter(CallStatus::Attended);

    let participant_records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &not_attended, LATEST_FIRST)
        .await?;
    assert!(participant_records.is_empty());

    let missed_records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &not_attended, LATEST_FIRST)
        .await?;
    assert_eq!(missed_records.len(), 2);
    assert_records_have_status(&missed_records, CallStatus::Missed);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_attended_true_returns_only_joined(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let filter = attended_filter(true);

    // user-a is a participant in both CALL1 and CALL_ARCHIVED.
    let user_a_records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(user_a_records.len(), 2);
    assert!(user_a_records.iter().any(|r| r.call_id == CALL1));
    assert!(user_a_records.iter().any(|r| r.call_id == CALL_ARCHIVED));

    // user-c is a channel member but did not join any call.
    let user_c_records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert!(
        user_c_records.is_empty(),
        "user-c attended none of the calls"
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_attended_false_returns_only_not_joined(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let filter = attended_filter(false);

    // user-a joined every call, so attended=false should return nothing.
    let user_a_records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert!(
        user_a_records.is_empty(),
        "user-a attended every fixture call"
    );

    // user-c joined none of the calls, so both should appear.
    let user_c_records = repo
        .get_call_records_by_user(USER_C.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(user_c_records.len(), 2);
    assert!(user_c_records.iter().any(|r| r.call_id == CALL1));
    assert!(user_c_records.iter().any(|r| r.call_id == CALL_ARCHIVED));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_attended_none_returns_all(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // Sanity-check the default path: without the attended filter, the query
    // still returns every call the channel member can see.
    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;
    assert_eq!(records.len(), 2);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_call_ids_filter_narrows_results(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let filter = call_ids_filter(&[CALL_ARCHIVED]);
    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(records.len(), 1);
    assert_eq!(records[0].call_id, CALL_ARCHIVED);

    let filter = call_ids_filter(&[CALL1, CALL_ARCHIVED]);
    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(records.len(), 2);

    let filter = call_ids_filter(&[Uuid::nil()]);
    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert!(
        records.is_empty(),
        "no call should match an unrelated call id"
    );
    Ok(())
}

fn entity_ref_property_literal(definition_id: Uuid, entity_id: Uuid) -> CallLiteral {
    use item_filters::ast::properties::{EntityRefId, PropertiesLiteral, PropertyMatchValue};
    CallLiteral::Property(PropertiesLiteral {
        property_definition_id: definition_id,
        entity_type: None,
        value: PropertyMatchValue::EntityRef(EntityRefId::new(entity_id.to_string()).unwrap()),
    })
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_entity_ref_filter_matches_referencing_calls(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let companies = Uuid::from_u128(0x00000001_0000_0000_0000_00000000000c);
    let acme = Uuid::from_u128(0xac);
    let globex = Uuid::from_u128(0x61);
    sqlx::query(
        r#"INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
           VALUES ($1, $2, 'CALL_RECORD', $3, $4)"#,
    )
    .bind(Uuid::now_v7())
    .bind(CALL_ARCHIVED.to_string())
    .bind(companies)
    .bind(serde_json::json!({
        "type": "EntityReference",
        "value": [{ "entity_type": "COMPANY", "entity_id": acme.to_string() }]
    }))
    .execute(&pool)
    .await?;

    let filter: LiteralTree<CallLiteral> = Some(Arc::new(Expr::Literal(
        entity_ref_property_literal(companies, acme),
    )));
    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(
        records.iter().map(|r| r.call_id).collect::<Vec<_>>(),
        vec![CALL_ARCHIVED]
    );

    // Any referenced entity matches; another definition or entity does not.
    let filter: LiteralTree<CallLiteral> = Some(Arc::new(Expr::or(
        Expr::Literal(entity_ref_property_literal(companies, globex)),
        Expr::Literal(entity_ref_property_literal(companies, acme)),
    )));
    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
        .await?;
    assert_eq!(records.len(), 1);

    for literal in [
        entity_ref_property_literal(companies, globex),
        entity_ref_property_literal(Uuid::from_u128(0x13), acme),
    ] {
        let filter: LiteralTree<CallLiteral> = Some(Arc::new(Expr::Literal(literal)));
        let records = repo
            .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST)
            .await?;
        assert!(records.is_empty(), "unexpected match: {records:?}");
    }

    let matching = |filter: Expr<CallLiteral>| {
        let repo = &repo;
        async move {
            repo.get_call_records_by_user(
                USER_A.deref().copied(),
                10,
                &Some(Arc::new(filter)),
                LATEST_FIRST,
            )
            .await
            .map(|records| records.iter().map(|r| r.call_id).collect::<Vec<_>>())
        }
    };
    let acme_ref = || Expr::Literal(entity_ref_property_literal(companies, acme));
    let globex_ref = || Expr::Literal(entity_ref_property_literal(companies, globex));
    let missing_tag = || Expr::Literal(tag_property_literal(Uuid::from_u128(0x7a6)));

    // AND requires both references.
    assert!(
        matching(Expr::and(acme_ref(), globex_ref()))
            .await?
            .is_empty()
    );
    // NOT excludes the referencing call and keeps the others.
    assert!(
        !matching(Expr::is_not(acme_ref()))
            .await?
            .contains(&CALL_ARCHIVED)
    );
    assert!(
        matching(Expr::is_not(globex_ref()))
            .await?
            .contains(&CALL_ARCHIVED)
    );
    // A tag OR a reference matches on either.
    assert_eq!(
        matching(Expr::or(missing_tag(), acme_ref())).await?,
        vec![CALL_ARCHIVED]
    );
    assert!(
        matching(Expr::and(missing_tag(), acme_ref()))
            .await?
            .is_empty()
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_records_by_user_returns_archived_summary(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let summary = "AI-generated summary of the archived call.";
    sqlx::query!(
        r#"UPDATE call_records SET summary = $2 WHERE id = $1"#,
        CALL_ARCHIVED,
        summary,
    )
    .execute(&pool)
    .await?;

    let records = repo
        .get_call_records_by_user(USER_A.deref().copied(), 10, &None, LATEST_FIRST)
        .await?;

    let active = records
        .iter()
        .find(|r| r.call_id == CALL1)
        .expect("active call missing");
    assert!(active.is_active);
    assert!(active.summary.is_none());

    let archived = records
        .iter()
        .find(|r| r.call_id == CALL_ARCHIVED)
        .expect("archived call missing");
    assert!(!archived.is_active);
    assert_eq!(archived.summary.as_deref(), Some(summary));

    Ok(())
}

// -- delete_call_record -------------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn delete_call_record_cascades(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    // Sanity check: the archived call and its children exist before delete.
    let pre_participants: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM call_record_participants WHERE call_record_id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    let pre_transcripts: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM call_record_transcripts WHERE call_record_id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert!(pre_participants > 0);
    assert!(pre_transcripts > 0);

    repo.delete_call_record(&CALL_ARCHIVED).await?;

    // Record row is gone.
    let record = repo.get_call_record_by_call_id(&CALL_ARCHIVED).await?;
    assert!(record.is_none());

    // Cascade removed participants and transcripts.
    let remaining_participants: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM call_record_participants WHERE call_record_id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    let remaining_transcripts: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM call_record_transcripts WHERE call_record_id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(remaining_participants, 0);
    assert_eq!(remaining_transcripts, 0);
    // entity_access grants for the archived call must be cleaned up atomically.
    let remaining_grants: i64 = sqlx::query_scalar!(
        r#"SELECT COUNT(*) as "count!" FROM entity_access WHERE entity_id = $1 AND entity_type = 'call'"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(remaining_grants, 0);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn delete_call_record_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    // Non-existent id — should succeed without touching anything.
    repo.delete_call_record(&Uuid::now_v7()).await?;

    // Existing archived record must still be present.
    assert!(
        repo.get_call_record_by_call_id(&CALL_ARCHIVED)
            .await?
            .is_some()
    );
    Ok(())
}

// -- patch_call_record --------------------------------------------------------

const SP_ARCHIVED: &str = "00000000-0000-0000-0000-00000000sp02";

#[derive(Debug, Eq, PartialEq)]
struct StoredSharePermission {
    link_share: Option<String>,
    link_share_access_level: Option<String>,
}

async fn get_stored_share_permission(
    pool: &Pool<Postgres>,
    share_permission_id: &str,
) -> Result<StoredSharePermission, sqlx::Error> {
    sqlx::query_as!(
        StoredSharePermission,
        r#"
        SELECT
            "linkShare" AS "link_share?",
            "linkShareAccessLevel"::text AS "link_share_access_level?"
        FROM "SharePermission"
        WHERE id = $1
        "#,
        share_permission_id,
    )
    .fetch_one(pool)
    .await
}

async fn set_stored_share_permission(
    pool: &Pool<Postgres>,
    link_share: Option<&str>,
    access_level: Option<&str>,
) -> Result<(), sqlx::Error> {
    sqlx::query!(
        r#"
        UPDATE "SharePermission"
        SET "linkShare" = $2, "linkShareAccessLevel" = $3::text::"AccessLevel"
        WHERE id = $1
        "#,
        SP_ARCHIVED,
        link_share,
        access_level,
    )
    .execute(pool)
    .await?;
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_sets_public_link_and_defaults_level_to_view(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: Some(Some(LinkShare::Public)),
                link_share_access_level: None,
                team_share_access_level: None,
                channel_share_permissions: None,
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;
    assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));
    assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_sets_team_link_and_explicit_level(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: Some(Some(LinkShare::Team)),
                link_share_access_level: Some(Some(AccessLevel::Edit)),
                team_share_access_level: None,
                channel_share_permissions: None,
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;
    assert_eq!(permission.link_share.as_deref(), Some("TEAM"));
    assert_eq!(permission.link_share_access_level.as_deref(), Some("edit"));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_explicit_null_disables_link_sharing(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    set_stored_share_permission(&pool, Some("PUBLIC"), Some("edit")).await?;

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: Some(None),
                link_share_access_level: Some(Some(AccessLevel::Edit)),
                team_share_access_level: None,
                channel_share_permissions: None,
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;
    assert_eq!(
        permission,
        StoredSharePermission {
            link_share: None,
            link_share_access_level: None,
        }
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_level_only_update_updates_link_share_access_level(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    set_stored_share_permission(&pool, Some("PUBLIC"), Some("view")).await?;

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: None,
                link_share_access_level: Some(Some(AccessLevel::Comment)),
                team_share_access_level: None,
                channel_share_permissions: None,
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let permission = get_stored_share_permission(&pool, SP_ARCHIVED).await?;
    assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));
    assert_eq!(
        permission.link_share_access_level.as_deref(),
        Some("comment")
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_adds_channel_share_permission(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let channel_id = CH2.to_string();

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: None,
                link_share_access_level: None,
                team_share_access_level: None,
                channel_share_permissions: Some(vec![UpdateChannelSharePermission {
                    operation: UpdateOperation::Add,
                    channel_id: channel_id.clone(),
                    access_level: Some(AccessLevel::View),
                }]),
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let csp_count = sqlx::query_scalar!(
        r#"
        SELECT COUNT(*) as "count!"
        FROM "ChannelSharePermission"
        WHERE share_permission_id = $1 AND channel_id = $2
        "#,
        SP_ARCHIVED,
        &channel_id,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(csp_count, 1);

    let access_rows = sqlx::query!(
        r#"
        SELECT source_id, access_level::text as "access_level", source_type::text as "source_type"
        FROM entity_access
        WHERE entity_id = $1
          AND entity_type = 'call'
          AND source_id = $2
          AND source_type = 'channel'
        "#,
        CALL_ARCHIVED,
        &channel_id,
    )
    .fetch_all(&pool)
    .await?;

    assert_eq!(access_rows.len(), 1);
    assert_eq!(access_rows[0].access_level.as_deref(), Some("view"));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_removes_channel_share_permission(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let channel_id = CH1.to_string();

    // Sanity: the fixture seeded a ChannelSharePermission for CH1.
    let pre_count = sqlx::query_scalar!(
        r#"
        SELECT COUNT(*) as "count!"
        FROM "ChannelSharePermission"
        WHERE share_permission_id = $1 AND channel_id = $2
        "#,
        SP_ARCHIVED,
        &channel_id,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(pre_count, 1);

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: None,
                link_share_access_level: None,
                team_share_access_level: None,
                channel_share_permissions: Some(vec![UpdateChannelSharePermission {
                    operation: UpdateOperation::Remove,
                    channel_id: channel_id.clone(),
                    access_level: None,
                }]),
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let post_count = sqlx::query_scalar!(
        r#"
        SELECT COUNT(*) as "count!"
        FROM "ChannelSharePermission"
        WHERE share_permission_id = $1 AND channel_id = $2
        "#,
        SP_ARCHIVED,
        &channel_id,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(post_count, 0);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_empty_share_permission_update_is_noop(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    set_stored_share_permission(&pool, Some("TEAM"), Some("comment")).await?;
    let before = get_stored_share_permission(&pool, SP_ARCHIVED).await?;

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: Some(UpdateSharePermissionRequestV2 {
                link_share: None,
                link_share_access_level: None,
                team_share_access_level: None,
                channel_share_permissions: None,
            }),
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let after = get_stored_share_permission(&pool, SP_ARCHIVED).await?;
    assert_eq!(before, after);
    Ok(())
}

// -- patch_call_record: custom_name -------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_sets_custom_name_on_archived_record(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: None,
            team_share: None,
            live_share_with_team: None,
            custom_name: Some("Q4 sync".to_string()),
        },
    )
    .await?;

    let stored = sqlx::query_scalar!(
        r#"SELECT custom_name FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(stored.as_deref(), Some("Q4 sync"));

    let record = repo.get_call_record_by_call_id(&CALL_ARCHIVED).await?;
    assert_eq!(
        record.and_then(|r| r.custom_name).as_deref(),
        Some("Q4 sync"),
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_custom_name_overwrites_existing(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    sqlx::query!(
        r#"UPDATE call_records SET custom_name = $2 WHERE id = $1"#,
        CALL_ARCHIVED,
        "Old name",
    )
    .execute(&pool)
    .await?;

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: None,
            team_share: None,
            live_share_with_team: None,
            custom_name: Some("New name".to_string()),
        },
    )
    .await?;

    let stored = sqlx::query_scalar!(
        r#"SELECT custom_name FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(stored.as_deref(), Some("New name"));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_custom_name_empty_string_clears_existing(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    sqlx::query!(
        r#"UPDATE call_records SET custom_name = $2 WHERE id = $1"#,
        CALL_ARCHIVED,
        "Existing",
    )
    .execute(&pool)
    .await?;

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: None,
            team_share: None,
            live_share_with_team: None,
            custom_name: Some(String::new()),
        },
    )
    .await?;

    let stored = sqlx::query_scalar!(
        r#"SELECT custom_name FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(stored, None);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_record_custom_name_none_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    sqlx::query!(
        r#"UPDATE call_records SET custom_name = $2 WHERE id = $1"#,
        CALL_ARCHIVED,
        "Existing",
    )
    .execute(&pool)
    .await?;

    repo.patch_call_record(
        &CALL_ARCHIVED,
        &EditCallRecordRepoArgs {
            share_permission: None,
            team_share: None,
            live_share_with_team: None,
            custom_name: None,
        },
    )
    .await?;

    let stored = sqlx::query_scalar!(
        r#"SELECT custom_name FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(stored.as_deref(), Some("Existing"));
    Ok(())
}

// -- set_custom_name_if_null --------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn set_custom_name_if_null_writes_when_column_is_null(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    let persisted = repo
        .set_custom_name_if_null(&CALL_ARCHIVED, "AI Generated Name")
        .await?;

    assert!(persisted);
    let stored = sqlx::query_scalar!(
        r#"SELECT custom_name FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(stored.as_deref(), Some("AI Generated Name"));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn set_custom_name_if_null_does_not_overwrite_existing_name(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    sqlx::query!(
        r#"UPDATE call_records SET custom_name = $2 WHERE id = $1"#,
        CALL_ARCHIVED,
        "User Picked",
    )
    .execute(&pool)
    .await?;

    let persisted = repo
        .set_custom_name_if_null(&CALL_ARCHIVED, "AI Generated")
        .await?;

    assert!(!persisted);
    let stored = sqlx::query_scalar!(
        r#"SELECT custom_name FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(stored.as_deref(), Some("User Picked"));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn set_custom_name_if_null_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    let persisted = repo
        .set_custom_name_if_null(&Uuid::now_v7(), "Whatever")
        .await?;

    assert!(!persisted);
    Ok(())
}

// -- insert_call_summary ------------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn insert_call_summary_sets_summary_text(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let summary = "A short synopsis of the call.";

    let persisted = repo.insert_call_summary(&CALL_ARCHIVED, summary).await?;

    assert!(persisted);
    let stored = sqlx::query_scalar!(
        r#"SELECT summary FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;

    assert_eq!(stored.as_deref(), Some(summary));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn insert_call_summary_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    let persisted = repo
        .insert_call_summary(&Uuid::now_v7(), "irrelevant")
        .await?;

    assert!(!persisted);
    // The archived fixture row must remain untouched.
    let stored = sqlx::query_scalar!(
        r#"SELECT summary FROM call_records WHERE id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert!(stored.is_none());
    Ok(())
}

// -- get_call_participants_with_team_members ----------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_participants_with_team_members_returns_distinct_users(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    let team_id = Uuid::from_u128(0x00000000_0000_0000_0000_00000000beef);

    insert_user_mapping(&pool, USER_A.deref(), MACRO_USER_A).await?;
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;

    sqlx::query!(
        r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#,
        team_id,
        "speaker candidates",
        USER_A.deref().as_ref(),
    )
    .execute(&pool)
    .await?;

    sqlx::query!(
        r#"
        INSERT INTO team_user (user_id, team_id, team_role) VALUES
            ($1, $2, 'owner'),
            ($3, $2, 'member'),
            ($4, $2, 'member')
        "#,
        USER_A.deref().as_ref(),
        team_id,
        USER_B.deref().as_ref(),
        USER_C.deref().as_ref(),
    )
    .execute(&pool)
    .await?;

    let users = repo
        .get_call_participants_with_team_members(&CALL_ARCHIVED)
        .await?;
    let user_ids: Vec<String> = users
        .into_iter()
        .map(|user_id| user_id.as_ref().to_string())
        .collect();

    assert_eq!(
        user_ids,
        vec![
            "macro|[email protected]".to_string(),
            "macro|[email protected]".to_string(),
            "macro|[email protected]".to_string(),
        ]
    );
    Ok(())
}

// -- get_call_record_people ---------------------------------------------------

/// Inserts an hour-long event starting at `starts_at` and returns its id.
async fn insert_calendar_event_with_attendees(
    pool: &Pool<Postgres>,
    owner_id: &str,
    location: &str,
    starts_at: &str,
    attendees: &[&str],
) -> anyhow::Result<Uuid> {
    let link_id = Uuid::now_v7();
    sqlx::query(
        r#"
        INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
        VALUES ($1, $2, $2, $1::text || '@example.com', 'GMAIL')
        "#,
    )
    .bind(link_id)
    .bind(owner_id)
    .execute(pool)
    .await?;
    let event_id = Uuid::now_v7();
    sqlx::query(
        r#"
        INSERT INTO calendar_events (
            id, owner_id, source_link_id, ical_uid, title, location,
            canonical_source_kind, starts_at, ends_at
        )
        VALUES (
            $1, $2, $3, $1::text, 'Intro', $4, 'google',
            $5::timestamptz, $5::timestamptz + interval '1 hour'
        )
        "#,
    )
    .bind(event_id)
    .bind(owner_id)
    .bind(link_id)
    .bind(location)
    .bind(starts_at)
    .execute(pool)
    .await?;
    for email in attendees {
        sqlx::query("INSERT INTO calendar_event_attendees (event_id, email) VALUES ($1, $2)")
            .bind(event_id)
            .bind(email)
            .execute(pool)
            .await?;
    }
    Ok(event_id)
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_people_returns_participants_only_without_a_meeting(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let people = repo(pool).get_call_record_people(&CALL_ARCHIVED).await?;

    let mut user_ids: Vec<String> = people.user_ids.iter().map(ToString::to_string).collect();
    user_ids.sort();
    assert_eq!(
        user_ids,
        vec!["macro|[email protected]", "macro|[email protected]"]
    );
    assert!(people.invitee_emails.is_empty());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_people_skips_unparsable_participant_ids(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    sqlx::query(
        "INSERT INTO call_record_participants (call_record_id, user_id, joined_at) VALUES ($1, 'not-a-user-id', now())",
    )
    .bind(CALL_ARCHIVED)
    .execute(&pool)
    .await?;

    let people = repo(pool).get_call_record_people(&CALL_ARCHIVED).await?;

    let mut user_ids: Vec<String> = people.user_ids.iter().map(ToString::to_string).collect();
    user_ids.sort();
    assert_eq!(
        user_ids,
        vec!["macro|[email protected]", "macro|[email protected]"]
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_call_record_people_includes_meeting_owner_and_calendar_invitees(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;
    insert_user_mapping(&pool, USER_D.deref(), Uuid::now_v7()).await?;
    let meeting_id = Uuid::now_v7();
    sqlx::query(
        "INSERT INTO call_meetings (id, share_token, user_id, title) VALUES ($1, 'tok-crm-link', $2, 'Intro')",
    )
    .bind(meeting_id)
    .bind(USER_C.deref().as_ref())
    .execute(&pool)
    .await?;
    sqlx::query("UPDATE call_records SET meeting_id = $1 WHERE id = $2")
        .bind(meeting_id)
        .bind(CALL_ARCHIVED)
        .execute(&pool)
        .await?;
    // The fixture's archived call ran 2024-01-01 10:00-10:05.
    const LINK: &str = "https://macro.com/app/meet/join/tok-crm-link";
    insert_calendar_event_with_attendees(
        &pool,
        USER_C.deref().as_ref(),
        LINK,
        "2024-01-01 10:00:00+00",
        &["[email protected]", "[email protected]"],
    )
    .await?;
    // A weekly series started earlier, whose occurrence overlaps the call.
    let series = insert_calendar_event_with_attendees(
        &pool,
        USER_C.deref().as_ref(),
        LINK,
        "2023-12-04 10:00:00+00",
        &["[email protected]"],
    )
    .await?;
    sqlx::query(
        r#"INSERT INTO calendar_event_occurrences (event_id, owner_id, occurrence_key, starts_at, ends_at)
           VALUES ($1, $2, 'weekly-2024-01-01', '2024-01-01 09:30:00+00', '2024-01-01 10:30:00+00')"#,
    )
    .bind(series)
    .bind(USER_C.deref().as_ref())
    .execute(&pool)
    .await?;
    // An all-day event on the call's day counts; one days later does not.
    for (date, attendee) in [
        ("2024-01-01", "[email protected]"),
        ("2024-01-05", "[email protected]"),
    ] {
        let link_id = Uuid::now_v7();
        sqlx::query(
            r#"INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)
               VALUES ($1, $2, $2, $1::text || '@example.com', 'GMAIL')"#,
        )
        .bind(link_id)
        .bind(USER_C.deref().as_ref())
        .execute(&pool)
        .await?;
        let event_id = Uuid::now_v7();
        sqlx::query(
            r#"INSERT INTO calendar_events (
                   id, owner_id, source_link_id, ical_uid, title, location,
                   canonical_source_kind, start_date, end_date
               )
               VALUES ($1, $2, $3, $1::text, 'Offsite', $4, 'google', $5::date, $5::date + 1)"#,
        )
        .bind(event_id)
        .bind(USER_C.deref().as_ref())
        .bind(link_id)
        .bind(LINK)
        .bind(date)
        .execute(&pool)
        .await?;
        sqlx::query("INSERT INTO calendar_event_attendees (event_id, email) VALUES ($1, $2)")
            .bind(event_id)
            .bind(attendee)
            .execute(&pool)
            .await?;
    }
    // The same reused link at another time, the owner's events without the
    // link, and other owners' copies are ignored.
    insert_calendar_event_with_attendees(
        &pool,
        USER_C.deref().as_ref(),
        LINK,
        "2024-01-08 10:00:00+00",
        &["[email protected]"],
    )
    .await?;
    insert_calendar_event_with_attendees(
        &pool,
        USER_C.deref().as_ref(),
        "Room 1",
        "2024-01-01 10:00:00+00",
        &["[email protected]"],
    )
    .await?;
    insert_calendar_event_with_attendees(
        &pool,
        USER_D.deref().as_ref(),
        LINK,
        "2024-01-01 10:00:00+00",
        &["[email protected]"],
    )
    .await?;

    let people = repo(pool).get_call_record_people(&CALL_ARCHIVED).await?;

    let mut user_ids: Vec<String> = people.user_ids.iter().map(ToString::to_string).collect();
    user_ids.sort();
    assert_eq!(
        user_ids,
        vec![
            "macro|[email protected]",
            "macro|[email protected]",
            "macro|[email protected]"
        ]
    );
    let mut invitee_emails = people.invitee_emails;
    invitee_emails.sort();
    assert_eq!(
        invitee_emails,
        vec![
            "[email protected]",
            "[email protected]",
            "[email protected]",
            "[email protected]"
        ]
    );
    Ok(())
}

// -- get_enhanced_call_record_transcripts -------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_enhanced_call_record_transcripts_returns_archived_rows(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let transcripts = repo
        .get_enhanced_call_record_transcripts(&CALL_ARCHIVED)
        .await?;

    assert_eq!(transcripts.len(), 3);
    assert_eq!(transcripts[0].call_record_id, CALL_ARCHIVED);
    assert_eq!(transcripts[0].segment_id.as_deref(), Some("seg-arch-1"));
    assert_eq!(transcripts[0].speaker_id, "macro|[email protected]");
    assert_eq!(
        transcripts[0].diarized_speaker_id.as_deref(),
        Some("spk-arch-a0")
    );
    assert!(transcripts[0].custom_speaker.is_none());
    assert!(transcripts[0].voice_id.is_none());
    assert_eq!(transcripts[0].content, "archived hello");
    assert_eq!(transcripts[0].sequence_num, 1);

    assert_eq!(transcripts[2].segment_id.as_deref(), Some("seg-arch-3"));
    assert_eq!(
        transcripts[2].custom_speaker.as_deref(),
        Some(USER_B.deref().as_ref())
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn get_enhanced_call_record_transcripts_unknown_call_returns_empty(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let transcripts = repo
        .get_enhanced_call_record_transcripts(&Uuid::now_v7())
        .await?;

    assert!(transcripts.is_empty());
    Ok(())
}

// -- overwrite_custom_speakers ------------------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn overwrite_custom_speakers_sets_rows_by_transcript_id(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    let rows = sqlx::query!(
        r#"
        SELECT id
        FROM call_record_transcripts
        WHERE call_record_id = $1
        ORDER BY sequence_num ASC
        "#,
        CALL_ARCHIVED,
    )
    .fetch_all(&pool)
    .await?;
    let first_id = rows[0].id;
    let second_id = rows[1].id;

    repo.overwrite_custom_speakers(vec![
        (first_id, USER_C.deref().to_string()),
        (second_id, USER_A.deref().to_string()),
    ])
    .await?;

    let stored = sqlx::query!(
        r#"
        SELECT custom_speaker
        FROM call_record_transcripts
        WHERE call_record_id = $1
        ORDER BY sequence_num ASC
        "#,
        CALL_ARCHIVED,
    )
    .fetch_all(&pool)
    .await?;

    let first_custom_speaker = stored[0].custom_speaker.as_deref();
    let second_custom_speaker = stored[1].custom_speaker.as_deref();
    let third_custom_speaker = stored[2].custom_speaker.as_deref();

    assert_eq!(first_custom_speaker, Some(USER_C.deref().as_ref()));
    assert_eq!(second_custom_speaker, Some(USER_A.deref().as_ref()));
    assert_eq!(third_custom_speaker, Some(USER_B.deref().as_ref()));
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn overwrite_custom_speakers_empty_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool.clone());

    repo.overwrite_custom_speakers(Vec::new()).await?;

    let count = sqlx::query_scalar!(
        r#"SELECT COUNT(*) AS "count!" FROM call_record_transcripts WHERE call_record_id = $1"#,
        CALL_ARCHIVED,
    )
    .fetch_one(&pool)
    .await?;
    assert_eq!(count, 3);
    Ok(())
}

// -- patch_call_transcript_custom_speakers ------------------------------------

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_transcript_custom_speakers_sets_and_clears(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // Set: pin diarized `spk-arch-a0` to user-c. The fixture's seg-arch-3 row
    // (diarized `spk-arch-b0`) already has user-b as its custom_speaker — clear it.
    repo.patch_call_transcript_custom_speakers(
        &CALL_ARCHIVED,
        &[
            CustomSpeakerAssignment {
                diarized_speaker_id: "spk-arch-a0".to_string(),
                custom_speaker: Some(USER_C.clone()),
            },
            CustomSpeakerAssignment {
                diarized_speaker_id: "spk-arch-b0".to_string(),
                custom_speaker: None,
            },
        ],
    )
    .await?;

    let record = repo
        .get_call_record_by_call_id(&CALL_ARCHIVED)
        .await?
        .expect("archived call should exist");

    // seg-arch-1 (diarized spk-arch-a0): override now applied → user-c.
    assert_eq!(record.transcript[0].content, "archived hello");
    assert_eq!(record.transcript[0].speaker_id, "macro|[email protected]");

    // seg-arch-2 (diarized NULL): never touched.
    assert_eq!(record.transcript[1].content, "archived reply");
    assert_eq!(record.transcript[1].speaker_id, "macro|[email protected]");

    // seg-arch-3 (diarized spk-arch-b0): override cleared → derived speaker_id wins.
    assert_eq!(record.transcript[2].content, "archived overridden");
    assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");

    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_transcript_custom_speakers_empty_is_noop(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    repo.patch_call_transcript_custom_speakers(&CALL_ARCHIVED, &[])
        .await?;

    // Fixture state is unchanged.
    let record = repo
        .get_call_record_by_call_id(&CALL_ARCHIVED)
        .await?
        .expect("archived call should exist");
    assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn patch_call_transcript_custom_speakers_unknown_diarized_id_is_noop(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    // Diarized id that doesn't exist in this call: silently affects nothing.
    repo.patch_call_transcript_custom_speakers(
        &CALL_ARCHIVED,
        &[CustomSpeakerAssignment {
            diarized_speaker_id: "spk-does-not-exist".to_string(),
            custom_speaker: Some(USER_C.clone()),
        }],
    )
    .await?;

    let record = repo
        .get_call_record_by_call_id(&CALL_ARCHIVED)
        .await?
        .expect("archived call should exist");
    // All rows still reflect their original speaker_id / custom_speaker.
    assert_eq!(record.transcript[0].speaker_id, "macro|[email protected]");
    assert_eq!(record.transcript[1].speaker_id, "macro|[email protected]");
    assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");
    Ok(())
}

fn standalone_meeting() -> crate::domain::meetings::Meeting {
    crate::domain::meetings::Meeting {
        id: Uuid::now_v7(),
        share_token: crate::domain::meetings::MeetingToken::generate(),
        title: "Design review".to_string(),
        scheduled_start: None,
        scheduled_end: None,
        channel_id: None,
        channel_call_id: None,
        call_id: None,
        user_id: USER_B.to_string(),
    }
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn live_call_join_access_requires_membership_or_invitation(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;
    insert_user_mapping(&pool, USER_D.deref(), Uuid::now_v7()).await?;
    let repo = repo(pool);

    assert!(repo.can_join_call(&CALL1, USER_A.as_ref()).await?);
    assert!(repo.can_join_call(&CALL1, USER_C.as_ref()).await?);
    assert!(!repo.can_join_call(&CALL1, USER_D.as_ref()).await?);

    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let (call, _) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    assert!(repo.can_join_call(&call.id, USER_B.as_ref()).await?);
    assert!(!repo.can_join_call(&call.id, USER_C.as_ref()).await?);
    repo.add_meeting_participant(&call.id, USER_C.clone())
        .await?;
    repo.add_meeting_invitees(&meeting.id, &call.id, &[USER_D.clone()])
        .await?;
    assert!(repo.can_join_call(&call.id, USER_C.as_ref()).await?);
    assert!(repo.can_join_call(&call.id, USER_D.as_ref()).await?);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn program_only_call_waits_for_last_person_departure(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool.clone());
    repo.set_participant_client(&CALL1, USER_B.as_ref(), "agent")
        .await?;
    assert!(repo.archive_call_if_program_only(&CALL1).await?.is_none());

    repo.remove_participant(&CALL1, USER_A.clone()).await?;
    assert!(repo.archive_call_if_program_only(&CALL1).await?.is_none());

    sqlx::query!(
        "UPDATE call_participants SET left_at = now() - interval '2 minutes' WHERE call_id = $1 AND user_id = $2",
        CALL1, USER_A.as_ref(),
    )
    .execute(&pool)
    .await?;
    assert!(repo.archive_call_if_program_only(&CALL1).await?.is_some());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn standalone_meeting_archives_guest_names_and_preserves_invitation(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let repo = repo(pool);
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let (call, created) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    assert!(created);
    assert_eq!(call.channel_id, None);
    let guest_id = GuestId::generate();
    repo.add_guest(&call.id, guest_id, "Ada Guest").await?;
    assert_eq!(repo.get_participant_count(&call.id).await?, 1);
    assert!(repo.archive_call_if_empty(&call.id).await?.is_none());
    repo.reconcile_guest(&call.id, guest_id, false).await?;
    assert_eq!(repo.get_participant_count(&call.id).await?, 0);
    repo.archive_call(&call.id).await?;
    let record = repo.get_call_record_by_call_id(&call.id).await?.unwrap();
    assert_eq!(record.channel_id, None);
    assert_eq!(record.custom_name.as_deref(), Some("Design review"));
    // Guests archive as their own rows; participant tables stay Macro-only.
    assert!(record.participants.is_empty());
    assert_eq!(record.guests.len(), 1);
    assert_eq!(record.guests[0].id, guest_id);
    assert_eq!(record.guests[0].display_name, "Ada Guest");
    assert!(record.guests[0].left_at.is_some());
    assert!(
        repo.get_call_participants_with_team_members(&call.id)
            .await?
            .is_empty()
    );
    assert_eq!(
        repo.get_meeting(&meeting.share_token)
            .await?
            .unwrap()
            .call_id,
        None
    );
    assert_eq!(
        repo.get_meeting_for_call(&call.id, false)
            .await?
            .unwrap()
            .id,
        meeting.id
    );
    let (next, created) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    assert!(created);
    assert_ne!(next.id, call.id);
    assert_ne!(next.room_name, call.room_name);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn guest_join_racing_archival_fails_instead_of_stranding_a_guest(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let repo = repo(pool);
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let (call, _) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    repo.archive_call(&call.id).await?;
    // The calls row is gone; the guest insert must fail loudly rather than
    // write a row for a room that no longer exists.
    assert!(
        repo.add_guest(&call.id, GuestId::generate(), "Ada")
            .await
            .is_err()
    );
    let record = repo.get_call_record_by_call_id(&call.id).await?.unwrap();
    assert!(record.guests.is_empty());
    // Late webhook reconciles for unknown guests are harmless no-ops on the
    // live table (the webhook path never reaches here once the call is gone).
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn concurrent_meeting_joins_allocate_exactly_one_session(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let repo = repo(pool);
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let first = Uuid::now_v7();
    let second = Uuid::now_v7();
    let (one, two) = tokio::join!(
        repo.get_or_create_meeting_call(&meeting.id, &first),
        repo.get_or_create_meeting_call(&meeting.id, &second)
    );
    let (one, created_one) = one?;
    let (two, created_two) = two?;
    assert_eq!(one.id, two.id);
    assert_ne!(created_one, created_two);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn meeting_cancellation_is_owner_only_and_revokes_join(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let repo = repo(pool);
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let request = || crate::domain::meetings::UpdateMeetingRequest {
        clear_schedule: false,
        title: Some("Updated review".to_string()),
        scheduled_start: None,
        scheduled_end: None,
    };
    assert!(
        repo.update_meeting(&meeting.id, USER_A.as_ref(), request())
            .await?
            .is_none()
    );
    let updated = repo
        .update_meeting(&meeting.id, USER_B.as_ref(), request())
        .await?
        .unwrap();
    assert_eq!(updated.title, "Updated review");
    assert_eq!(updated.share_token.as_str(), meeting.share_token.as_str());
    let start = Utc::now();
    repo.update_meeting(
        &meeting.id,
        USER_B.as_ref(),
        crate::domain::meetings::UpdateMeetingRequest {
            title: None,
            scheduled_start: Some(start),
            scheduled_end: Some(start + Duration::hours(1)),
            clear_schedule: false,
        },
    )
    .await?;
    let cleared = repo
        .update_meeting(
            &meeting.id,
            USER_B.as_ref(),
            crate::domain::meetings::UpdateMeetingRequest {
                title: None,
                scheduled_start: None,
                scheduled_end: None,
                clear_schedule: true,
            },
        )
        .await?
        .unwrap();
    assert!(cleared.scheduled_start.is_none());
    assert!(cleared.scheduled_end.is_none());
    assert!(!repo.cancel_meeting(&meeting.id, USER_A.as_ref()).await?);
    assert!(repo.get_meeting(&meeting.share_token).await?.is_some());
    assert!(repo.cancel_meeting(&meeting.id, USER_B.as_ref()).await?);
    assert!(repo.get_meeting(&meeting.share_token).await?.is_none());
    assert!(
        repo.get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
            .await
            .is_err()
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn channel_invitation_is_pinned_to_original_session(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let repo = repo(pool);
    let mut meeting = standalone_meeting();
    meeting.channel_id = Some(CH1);
    meeting.channel_call_id = Some(CALL1);
    meeting.call_id = Some(CALL1);
    let meeting = repo.create_meeting(meeting).await?;
    repo.archive_call(&CALL1).await?;
    let resolved = repo.get_meeting(&meeting.share_token).await?.unwrap();
    assert_eq!(resolved.call_id, None);
    assert_eq!(resolved.channel_call_id, Some(CALL1));
    assert!(
        repo.get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
            .await
            .is_err()
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn authenticated_meeting_attendee_gets_only_call_access_and_owner_keeps_owner(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let attendee = MacroUserIdStr::try_from_email("[email protected]")?;
    insert_user_mapping(&pool, &attendee, Uuid::now_v7()).await?;
    let repo = repo(pool.clone());
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let (call, _) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    repo.add_meeting_participant(&call.id, attendee.copied())
        .await?;
    repo.remove_participant(&CALL1, USER_B.deref().copied())
        .await?;
    repo.add_meeting_participant(&call.id, USER_B.deref().copied())
        .await?;
    for (user, expected) in [
        (attendee.as_ref(), AccessLevel::Comment),
        (USER_B.as_ref(), AccessLevel::Owner),
    ] {
        let level = sqlx::query_scalar!(
            r#"SELECT access_level AS "access_level!: AccessLevel" FROM entity_access WHERE entity_id = $1 AND entity_type = 'call' AND source_id = $2 AND source_type = 'user' AND granted_from_project_id IS NULL"#,
            call.id, user,
        ).fetch_one(&pool).await?;
        assert_eq!(level, expected);
    }
    let channel_access = sqlx::query_scalar!(
        "SELECT EXISTS(SELECT 1 FROM entity_access WHERE entity_type = 'channel' AND source_id = $1) OR EXISTS(SELECT 1 FROM comms_channel_participants WHERE user_id = $1) AS \"exists!\"",
        attendee.as_ref(),
    ).fetch_one(&pool).await?;
    assert!(!channel_access);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn standalone_archive_never_translates_pending_intent_into_team_memory(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    give_user_a_team(&pool, USER_B.as_ref(), &Uuid::now_v7()).await?;
    let repo = repo(pool.clone());
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let (call, _) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    assert!(
        !repo
            .get_call_record_by_call_id(&call.id)
            .await?
            .unwrap()
            .share_with_team
    );
    // Simulate an old or internal writer; archival must still enforce the policy.
    repo.patch_call_record(
        &call.id,
        &EditCallRecordRepoArgs {
            share_permission: None,
            custom_name: None,
            team_share: None,
            live_share_with_team: Some(true),
        },
    )
    .await?;
    repo.archive_call(&call.id).await?;

    let record = repo.get_call_record_by_call_id(&call.id).await?.unwrap();
    assert!(!record.share_with_team);
    assert_eq!(record.team_share_access_level, None);
    assert_eq!(team_entity_access_count(&pool, call.id).await?, 0);
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn standalone_call_list_requires_individual_grants_live_and_archived(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    use entity_access_db_utils::{EntityAccessSourceType, EntityType, insert_entity_access_row};

    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    insert_user_mapping(&pool, USER_D.deref(), Uuid::now_v7()).await?;
    let team_id = Uuid::now_v7();
    give_user_a_team(&pool, USER_C.deref().as_ref(), &team_id).await?;
    let repo = repo(pool.clone());
    let meeting = repo.create_meeting(standalone_meeting()).await?;
    let (call, _) = repo
        .get_or_create_meeting_call(&meeting.id, &Uuid::now_v7())
        .await?;
    repo.add_meeting_participant(&call.id, USER_D.deref().copied())
        .await?;

    // Neither an old team grant nor sharing to an unrelated channel makes this
    // standalone call discoverable. Individual owner and attendee access remains.
    let mut tx = pool.begin().await?;
    for (source, source_type) in [
        (team_id, EntityAccessSourceType::Team),
        (CH1, EntityAccessSourceType::Channel),
    ] {
        insert_entity_access_row(
            &mut tx,
            &call.id,
            EntityType::Call,
            &source.to_string(),
            source_type,
            AccessLevel::View,
        )
        .await?;
    }
    tx.commit().await?;

    for archived in [false, true] {
        if archived {
            repo.archive_call(&call.id).await?;
        }
        for (user, expected) in [
            (USER_A.deref(), false),
            (USER_C.deref(), false),
            (USER_B.deref(), true),
            (USER_D.deref(), true),
        ] {
            let records = repo
                .get_call_records_by_user(user.copied(), 10, &None, LATEST_FIRST)
                .await?;
            assert_eq!(
                records.iter().any(|record| record.call_id == call.id),
                expected,
                "user={user}, archived={archived}"
            );
        }
    }
    Ok(())
}

// -- resolve_channel_name_for_viewers -----------------------------------------

const DM_CHANNEL: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000d01);

async fn insert_named_user(
    pool: &Pool<Postgres>,
    user_id: &MacroUserIdStr<'_>,
    macro_user_id: Uuid,
    first_name: &str,
    last_name: &str,
) -> anyhow::Result<()> {
    insert_user_mapping(pool, user_id, macro_user_id).await?;
    sqlx::query!(
        r#"
        INSERT INTO macro_user_info (macro_user_id, first_name, last_name)
        VALUES ($1, $2, $3)
        ON CONFLICT (macro_user_id) DO UPDATE
        SET first_name = EXCLUDED.first_name, last_name = EXCLUDED.last_name
        "#,
        macro_user_id,
        first_name,
        last_name,
    )
    .execute(pool)
    .await?;
    Ok(())
}

async fn insert_dm_channel(
    pool: &Pool<Postgres>,
    channel_id: Uuid,
    participants: &[&MacroUserIdStr<'_>],
) -> anyhow::Result<()> {
    sqlx::query!(
        r#"
        INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at, updated_at)
        VALUES ($1, NULL, 'direct_message', NULL, $2, now(), now())
        "#,
        channel_id,
        participants[0].as_ref(),
    )
    .execute(pool)
    .await?;
    for participant in participants {
        sqlx::query!(
            r#"
            INSERT INTO comms_channel_participants (channel_id, user_id, role, joined_at)
            VALUES ($1, $2, 'member', now())
            "#,
            channel_id,
            participant.as_ref(),
        )
        .execute(pool)
        .await?;
    }
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn resolve_channel_name_for_viewers_names_a_dm_after_the_other_participant(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_named_user(&pool, USER_A.deref(), MACRO_USER_A, "Jacob", "Beckerman").await?;
    insert_named_user(&pool, USER_B.deref(), MACRO_USER_B, "Teo", "Nys").await?;
    insert_dm_channel(&pool, DM_CHANNEL, &[USER_A.deref(), USER_B.deref()]).await?;
    let repo = repo(pool);

    // User A (Jacob) starts the call; user B (Teo) is the only recipient.
    let names = repo
        .resolve_channel_name_for_viewers(&DM_CHANNEL, &[USER_B.deref().copied()])
        .await?;

    assert_eq!(
        names.get(USER_B.deref()).map(String::as_str),
        Some("Jacob Beckerman"),
        "the callee must see the caller's name, not their own"
    );

    // The caller's own view, which the old code pushed to everyone, is the
    // callee's name.
    assert_eq!(
        repo.resolve_channel_name(&DM_CHANNEL, USER_A.deref().copied())
            .await?
            .as_deref(),
        Some("Teo Nys")
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn resolve_channel_name_for_viewers_uses_the_stored_name_for_every_viewer(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let names = repo
        .resolve_channel_name_for_viewers(&CH1, &[USER_B.deref().copied(), USER_C.deref().copied()])
        .await?;

    assert_eq!(names.len(), 2);
    assert!(
        names.values().all(|name| name == "call-test-channel"),
        "named channels read the same to everyone: {names:?}"
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn resolve_channel_name_for_viewers_is_empty_for_unknown_channel_or_no_viewers(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);

    let unknown = repo
        .resolve_channel_name_for_viewers(&Uuid::now_v7(), &[USER_B.deref().copied()])
        .await?;
    assert!(unknown.is_empty());

    let no_viewers = repo.resolve_channel_name_for_viewers(&CH1, &[]).await?;
    assert!(no_viewers.is_empty());
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn meeting_schedule_rejects_partial_or_reversed_ranges(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
    let repo = repo(pool);
    let start = chrono::Utc::now();
    let end = start + chrono::Duration::hours(1);
    for (scheduled_start, scheduled_end) in [
        (Some(start), None),
        (None, Some(end)),
        (Some(end), Some(start)),
    ] {
        let mut meeting = standalone_meeting();
        meeting.scheduled_start = scheduled_start;
        meeting.scheduled_end = scheduled_end;
        assert!(repo.create_meeting(meeting).await.is_err());
    }
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn attach_meeting_recording_survives_archival(pool: Pool<Postgres>) -> anyhow::Result<()> {
    let repo = repo(pool);
    assert!(
        repo.attach_meeting_recording(&CALL1, "early-recording")
            .await?
    );
    repo.archive_call(&CALL1).await?;
    assert!(
        repo.get_call_record_by_egress_id("early-recording")
            .await?
            .is_some()
    );
    assert!(
        !repo
            .attach_meeting_recording(&CALL1, "late-recording")
            .await?
    );
    assert!(
        repo.get_call_record_by_egress_id("late-recording")
            .await?
            .is_some()
    );
    assert!(
        !repo
            .attach_meeting_recording(&Uuid::now_v7(), "missing-recording")
            .await?
    );
    Ok(())
}

#[sqlx::test(
    fixtures(path = "../../../fixtures", scripts("call_repo")),
    migrator = "MACRO_DB_MIGRATIONS"
)]
async fn attach_meeting_recording_racing_archival_keeps_the_recording(
    pool: Pool<Postgres>,
) -> anyhow::Result<()> {
    let repo = repo(pool);
    let (attachment, archival) = tokio::join!(
        repo.attach_meeting_recording(&CALL1, "racing-recording"),
        repo.archive_call(&CALL1),
    );
    attachment?;
    archival?;
    assert!(
        repo.get_call_record_by_egress_id("racing-recording")
            .await?
            .is_some()
    );
    Ok(())
}