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.

40.3 KB
Raw Blame
mod owner;

use std::time::Duration;

use agent::types::{ChatMessageContent, Role};
use chrono::Utc;
use entity_registry::{BotFacts, EntityRegistryResult, OwnerGrantPolicy};
use entity_registry_db_utils::OwnedEntityRegistrar;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model::chat::NewChatMessage;
use model_owner::Owner;
use models_permissions::share_permission::access_level::AccessLevel;
use models_permissions::share_permission::{
    LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,
};
use sqlx::postgres::PgRow;
use sqlx::{Pool, Postgres, Row};

use super::PgChatRepo;
use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatRepoArgs};
use crate::domain::ports::ChatRepo;

/// Sponsors every bot with the fixture user, so a bot owner also grants that user.
#[derive(Clone)]
pub(super) struct SponsoredByOwner;

impl BotFacts for SponsoredByOwner {
    async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {
        Ok(Some(Owner::User(
            MacroUserIdStr::parse_from_str("macro|[email protected]")
                .unwrap()
                .into_owned(),
        )))
    }
}

pub(super) type TestRepo = PgChatRepo<SponsoredByOwner>;

pub(super) fn test_repo(pool: Pool<Postgres>) -> TestRepo {
    PgChatRepo::new(
        pool,
        OwnedEntityRegistrar::new(OwnerGrantPolicy::new(SponsoredByOwner)),
    )
}

/// The no-team default permission for a chat — the repo persists whatever the
/// domain layer resolved, so tests pass it explicitly.
fn default_share_permission() -> SharePermissionV2 {
    SharePermissionV2::new_chat_share_permission(None)
}

const BOT_OWNER: &str = "bot|00000000-0000-0000-0000-00000000a1a1";
const TEAM_OWNER: &str = "00000000-0000-0000-0000-00000000a2a2";

/// Registers a non-user principal in `"User"` so the `Chat."userId"` foreign
/// key accepts it as an owner.
async fn insert_owner_principal(pool: &Pool<Postgres>, principal: &str, macro_user_id: &str) {
    let macro_user_id = uuid::Uuid::parse_str(macro_user_id).unwrap();
    sqlx::query(
        r#"
        INSERT INTO "macro_user" ("id", "username", "email", "stripe_customer_id")
        VALUES ($1, $2, $3, $4)
        "#,
    )
    .bind(macro_user_id)
    .bind(principal)
    .bind(format!("{macro_user_id}@example.com"))
    .bind(format!("stripe_{macro_user_id}"))
    .execute(pool)
    .await
    .unwrap();
    sqlx::query(r#"INSERT INTO "User" ("id", "email", "macro_user_id") VALUES ($1, $2, $3)"#)
        .bind(principal)
        .bind(format!("{macro_user_id}@example.com"))
        .bind(macro_user_id)
        .execute(pool)
        .await
        .unwrap();
}

async fn set_chat_owner(pool: &Pool<Postgres>, chat_id: &str, owner: &str) {
    sqlx::query(r#"UPDATE "Chat" SET "userId" = $1 WHERE id = $2"#)
        .bind(owner)
        .bind(chat_id)
        .execute(pool)
        .await
        .unwrap();
}

async fn chat_history_count(pool: &Pool<Postgres>, chat_id: &str) -> i64 {
    let count: (i64,) = sqlx::query_as(
        r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,
    )
    .bind(chat_id)
    .fetch_one(pool)
    .await
    .unwrap();
    count.0
}

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

async fn get_stored_share_permission(
    pool: &Pool<Postgres>,
    chat_id: &str,
) -> StoredSharePermission {
    let row = sqlx::query!(
        r#"
        SELECT
            sp.id,
            sp."linkShare" AS "link_share?",
            sp."linkShareAccessLevel"::text AS "link_share_access_level?"
        FROM "ChatPermission" cp
        JOIN "SharePermission" sp ON cp."sharePermissionId" = sp.id
        WHERE cp."chatId" = $1
        "#,
        chat_id,
    )
    .fetch_one(pool)
    .await
    .unwrap();

    StoredSharePermission {
        id: row.id,
        link_share: row.link_share,
        link_share_access_level: row.link_share_access_level,
    }
}

async fn create_test_chat(repo: &TestRepo, name: &str) -> String {
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    repo.create(
        Owner::User(user_id),
        CreateChatArgs {
            name: name.to_string(),
            project_id: None,
        },
        default_share_permission(),
    )
    .await
    .unwrap()
}

async fn patch_share_permission(
    repo: &TestRepo,
    chat_id: &str,
    share_permission: UpdateSharePermissionRequestV2,
) {
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    repo.patch(
        user_id,
        chat_id,
        PatchChatRepoArgs {
            name: None,
            project_id: None,
            share_permission: Some(share_permission),
            team_share: None,
        },
    )
    .await
    .unwrap();
}

async fn create_chat_with_message(repo: &TestRepo) -> (String, String) {
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Message update test".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();
    let now = Utc::now();
    let message_id = crate::domain::ports::MessageRepo::create(
        repo,
        &chat_id,
        NewChatMessage {
            id: None,
            content: ChatMessageContent::Text("initial content".to_string()),
            role: Role::User,
            attachments: None,
            model: "test-model".to_string(),
            created_at: now,
            updated_at: now,
        },
    )
    .await
    .unwrap();

    (chat_id, message_id)
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_returns_id(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Test Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    assert!(!chat_id.is_empty());

    // verify the chat row exists
    let row = sqlx::query(r#"SELECT "userId", name FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(row.get::<String, _>("name"), "Test Chat");
    assert_eq!(row.get::<String, _>("userId"), "macro|[email protected]");
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_message_updates_chat_timestamp_and_selected_model(pool: Pool<Postgres>) {
    let repo = test_repo(pool);
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Active Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();
    let original_updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;
    let now = Utc::now();
    crate::domain::ports::MessageRepo::create(
        &repo,
        &chat_id,
        NewChatMessage {
            id: None,
            content: ChatMessageContent::Text("hello".to_string()),
            role: Role::User,
            attachments: None,
            model: "test-model".to_string(),
            created_at: now,
            updated_at: now,
        },
    )
    .await
    .unwrap();

    let updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();
    assert!(updated_at > original_updated_at);
    assert_eq!(
        repo.get_metadata(&chat_id).await.unwrap().model.as_deref(),
        Some("test-model")
    );

    for (role, model) in [(Role::User, "new-model"), (Role::Assistant, "test-model")] {
        let now = Utc::now();
        crate::domain::ports::MessageRepo::create(
            &repo,
            &chat_id,
            NewChatMessage {
                id: None,
                content: ChatMessageContent::Text("another message".to_owned()),
                role,
                attachments: None,
                model: model.to_owned(),
                created_at: now,
                updated_at: now,
            },
        )
        .await
        .unwrap();
        // An older reply finishing after a new send must not undo its model selection.
        assert_eq!(
            repo.get_metadata(&chat_id).await.unwrap().model.as_deref(),
            Some("new-model")
        );
    }
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn delete_message_returns_parent_chat_id_and_removes_message(pool: Pool<Postgres>) {
    let repo = test_repo(pool);
    let (chat_id, message_id) = create_chat_with_message(&repo).await;

    let deleted_from_chat_id = crate::domain::ports::MessageRepo::delete(&repo, &message_id)
        .await
        .unwrap();

    assert_eq!(deleted_from_chat_id, chat_id);
    assert!(matches!(
        crate::domain::ports::MessageRepo::get_message_content(&repo, &chat_id, &message_id).await,
        Err(ChatErr::NotFound)
    ));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn update_message_content_bumps_chat_updated_at(pool: Pool<Postgres>) {
    let repo = test_repo(pool);
    let (chat_id, message_id) = create_chat_with_message(&repo).await;
    let original_updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;
    repo.update_message_content(
        &chat_id,
        &message_id,
        &ChatMessageContent::Text("final content".to_string()),
    )
    .await
    .unwrap();

    let updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();
    assert!(updated_at > original_updated_at);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn update_interim_message_content_does_not_bump_chat(pool: Pool<Postgres>) {
    let repo = test_repo(pool);
    let (chat_id, message_id) = create_chat_with_message(&repo).await;
    let original_updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;
    repo.update_interim_message_content(
        &chat_id,
        &message_id,
        &ChatMessageContent::Text("interim content".to_string()),
    )
    .await
    .unwrap();

    let updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();
    assert_eq!(updated_at, original_updated_at);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn nonexistent_message_does_not_bump_chat(pool: Pool<Postgres>) {
    let repo = test_repo(pool);
    let (chat_id, _) = create_chat_with_message(&repo).await;
    let original_updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();

    tokio::time::sleep(Duration::from_millis(10)).await;
    repo.update_message_content(
        &chat_id,
        "nonexistent-message",
        &ChatMessageContent::Text("final content".to_string()),
    )
    .await
    .unwrap();

    let updated_at = repo
        .get_metadata(&chat_id)
        .await
        .unwrap()
        .updated_at
        .unwrap();
    assert_eq!(updated_at, original_updated_at);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_creates_public_view_permission(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Perm Chat").await;

    let permission = get_stored_share_permission(&pool, &chat_id).await;
    assert!(!permission.id.is_empty());
    assert_eq!(permission.link_share.as_deref(), Some("PUBLIC"));
    assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_creates_user_item_access(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Access Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let row = sqlx::query(
        r#"
        SELECT "access_level"::text as "access_level"
        FROM "entity_access"
        WHERE "source_id" = $1 AND "entity_id" = $2
        "#,
    )
    .bind("macro|[email protected]")
    .bind(macro_uuid::string_to_uuid(&chat_id).unwrap())
    .fetch_one(&pool)
    .await
    .unwrap();

    assert_eq!(
        row.get::<Option<String>, _>("access_level"),
        Some("owner".to_string())
    );
}

async fn fetch_entity_row(pool: &Pool<Postgres>, chat_id: &str) -> PgRow {
    sqlx::query(
        r#"
        SELECT
            owner_type::text AS owner_type,
            owner_id,
            entity_type,
            deleted_at
        FROM entity
        WHERE id = $1
        "#,
    )
    .bind(macro_uuid::string_to_uuid(chat_id).unwrap())
    .fetch_one(pool)
    .await
    .unwrap()
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_registers_entity_row(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Entity Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let row = fetch_entity_row(&pool, &chat_id).await;
    assert_eq!(row.get::<String, _>("owner_type"), "user");
    assert_eq!(row.get::<String, _>("owner_id"), "macro|[email protected]");
    assert_eq!(row.get::<String, _>("entity_type"), "chat");
    assert_eq!(
        row.get::<Option<chrono::DateTime<Utc>>, _>("deleted_at"),
        None
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn delete_chat_marks_entity_deleted(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Entity Soft Delete").await;

    repo.delete(&chat_id).await.unwrap();

    let row = fetch_entity_row(&pool, &chat_id).await;
    assert!(
        row.get::<Option<chrono::DateTime<Utc>>, _>("deleted_at")
            .is_some()
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn revert_delete_clears_entity_deleted_at(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Entity Restore").await;

    repo.delete(&chat_id).await.unwrap();
    repo.revert_delete(&chat_id, None).await.unwrap();

    let row = fetch_entity_row(&pool, &chat_id).await;
    assert_eq!(
        row.get::<Option<chrono::DateTime<Utc>>, _>("deleted_at"),
        None
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_entity_row(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Entity Perm Delete").await;

    repo.permanently_delete(&chat_id).await.unwrap();

    let count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM entity WHERE id = $1"#)
        .bind(macro_uuid::string_to_uuid(&chat_id).unwrap())
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(count.0, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn copy_chat_registers_entity_row_for_source_and_copy(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let source_id = repo
        .create(
            Owner::User(user_id.clone()),
            CreateChatArgs {
                name: "Entity Source".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let copied_id = repo
        .copy_chat(
            Owner::User(user_id),
            &source_id,
            CopyChatArgs {
                name: "Entity Copy".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    assert_ne!(source_id, copied_id);

    let source_row = fetch_entity_row(&pool, &source_id).await;
    let copy_row = fetch_entity_row(&pool, &copied_id).await;
    assert_eq!(source_row.get::<String, _>("entity_type"), "chat");
    assert_eq!(copy_row.get::<String, _>("entity_type"), "chat");
    assert_eq!(source_row.get::<String, _>("owner_type"), "user");
    assert_eq!(copy_row.get::<String, _>("owner_type"), "user");
    assert_eq!(
        source_row.get::<String, _>("owner_id"),
        "macro|[email protected]"
    );
    assert_eq!(
        copy_row.get::<String, _>("owner_id"),
        "macro|[email protected]"
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn delete_restore_and_purge_succeed_without_entity_row(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Legacy Chat").await;
    let chat_uuid = macro_uuid::string_to_uuid(&chat_id).unwrap();

    sqlx::query(r#"DELETE FROM entity WHERE id = $1"#)
        .bind(chat_uuid)
        .execute(&pool)
        .await
        .unwrap();

    repo.delete(&chat_id).await.unwrap();
    repo.revert_delete(&chat_id, None).await.unwrap();
    repo.permanently_delete(&chat_id).await.unwrap();

    let chat_count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();
    assert_eq!(chat_count.0, 0);

    let entity_count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM entity WHERE id = $1"#)
        .bind(chat_uuid)
        .fetch_one(&pool)
        .await
        .unwrap();
    assert_eq!(entity_count.0, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_creates_user_history(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "History Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let row = sqlx::query(
        r#"
        SELECT "itemType" FROM "UserHistory"
        WHERE "userId" = $1 AND "itemId" = $2
        "#,
    )
    .bind("macro|[email protected]")
    .bind(&chat_id)
    .fetch_one(&pool)
    .await
    .unwrap();

    assert_eq!(row.get::<String, _>("itemType"), "chat");
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn create_chat_with_project_id(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Project Chat".to_string(),
                project_id: Some("project-123".to_string()),
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let row = sqlx::query(r#"SELECT "projectId" FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(
        row.get::<Option<String>, _>("projectId"),
        Some("project-123".to_string())
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_returns_chat(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Get Me".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let chat = repo.get_metadata(&chat_id).await.unwrap();

    assert_eq!(chat.id, chat_id);
    assert_eq!(chat.name, "Get Me");
    assert_eq!(
        chat.user_id,
        Owner::from_principal_str("macro|[email protected]").unwrap()
    );
    assert!(chat.created_at.is_some());
    assert!(chat.updated_at.is_some());
    assert!(chat.deleted_at.is_none());
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_decodes_bot_and_team_owners(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Owned Elsewhere").await;
    insert_owner_principal(&pool, BOT_OWNER, "b1111111-1111-1111-1111-111111111111").await;
    insert_owner_principal(&pool, TEAM_OWNER, "b2222222-2222-2222-2222-222222222222").await;

    set_chat_owner(&pool, &chat_id, BOT_OWNER).await;
    let chat = repo.get_metadata(&chat_id).await.unwrap();
    assert_eq!(chat.user_id, Owner::from_principal_str(BOT_OWNER).unwrap());
    assert!(matches!(chat.user_id, Owner::Bot(_)));

    set_chat_owner(&pool, &chat_id, TEAM_OWNER).await;
    let chat = repo.get_metadata(&chat_id).await.unwrap();
    assert_eq!(chat.user_id, Owner::from_principal_str(TEAM_OWNER).unwrap());
    assert!(matches!(chat.user_id, Owner::Team(_)));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_not_found(pool: Pool<Postgres>) {
    let repo = test_repo(pool);

    let result = repo.get_metadata("nonexistent-id").await;
    assert!(matches!(result, Err(ChatErr::NotFound)));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn soft_delete_chat_sets_deleted_at(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Delete Me".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    repo.delete(&chat_id).await.unwrap();

    let row = sqlx::query(r#"SELECT "deletedAt" FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();

    let deleted_at: Option<chrono::NaiveDateTime> = row.get("deletedAt");
    assert!(deleted_at.is_some());
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn soft_delete_chat_removes_history(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "History Delete".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    repo.delete(&chat_id).await.unwrap();

    let count: (i64,) = sqlx::query_as(
        r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,
    )
    .bind(&chat_id)
    .fetch_one(&pool)
    .await
    .unwrap();

    assert_eq!(count.0, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_row(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Perm Delete".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    repo.permanently_delete(&chat_id).await.unwrap();

    let count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(count.0, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_permissions(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Perm Delete Perms".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    repo.permanently_delete(&chat_id).await.unwrap();

    let count: (i64,) =
        sqlx::query_as(r#"SELECT COUNT(*) FROM "ChatPermission" WHERE "chatId" = $1"#)
            .bind(&chat_id)
            .fetch_one(&pool)
            .await
            .unwrap();

    assert_eq!(count.0, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn permanently_delete_chat_removes_user_item_access(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Perm Delete Access".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    repo.permanently_delete(&chat_id).await.unwrap();

    let count: i64 = sqlx::query!(
        r#"SELECT COUNT(id) AS result FROM "entity_access" WHERE "entity_id" = $1"#,
        &macro_uuid::string_to_uuid(&chat_id).unwrap(),
    )
    .map(|r| r.result.unwrap_or(0))
    .fetch_one(&pool)
    .await
    .unwrap();

    assert_eq!(count, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_updates_name(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Original".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let patch_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    repo.patch(
        patch_user_id,
        &chat_id,
        PatchChatRepoArgs {
            name: Some("Renamed".to_string()),
            project_id: None,
            share_permission: None,
            team_share: None,
        },
    )
    .await
    .unwrap();

    let chat = repo.get_metadata(&chat_id).await.unwrap();
    assert_eq!(chat.name, "Renamed");
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_updates_project(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Project Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let patch_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    repo.patch(
        patch_user_id,
        &chat_id,
        PatchChatRepoArgs {
            name: None,
            project_id: Some("project-123".to_string()),
            share_permission: None,
            team_share: None,
        },
    )
    .await
    .unwrap();

    let row = sqlx::query(r#"SELECT "projectId" FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(
        row.get::<Option<String>, _>("projectId"),
        Some("project-123".to_string())
    );
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_clears_project(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Clear Project".to_string(),
                project_id: Some("project-123".to_string()),
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let patch_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    repo.patch(
        patch_user_id,
        &chat_id,
        PatchChatRepoArgs {
            name: None,
            project_id: Some("".to_string()),
            share_permission: None,
            team_share: None,
        },
    )
    .await
    .unwrap();

    let row = sqlx::query(r#"SELECT "projectId" FROM "Chat" WHERE id = $1"#)
        .bind(&chat_id)
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(row.get::<Option<String>, _>("projectId"), None::<String>);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_returns_full_response(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Full Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    let response = repo.get_chat(&chat_id).await.unwrap();

    assert_eq!(response.id, chat_id);
    assert_eq!(response.name, "Full Chat");
    assert_eq!(
        response.user_id,
        Owner::from_principal_str("macro|[email protected]").unwrap()
    );
    assert!(response.model.is_some());
    assert!(response.messages.is_empty());
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn get_chat_not_found_returns_error(pool: Pool<Postgres>) {
    let repo = test_repo(pool);

    let result = repo.get_chat("nonexistent-id").await;
    assert!(matches!(result, Err(ChatErr::NotFound)));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn copy_chat_creates_new_chat_with_same_messages(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let source_id = repo
        .create(
            Owner::User(user_id.clone()),
            CreateChatArgs {
                name: "Source Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    // Insert a message into the source chat
    sqlx::query(
        r#"
        INSERT INTO "ChatMessage" ("chatId", "content", "role")
        VALUES ($1, '"hello"', 'user')
        "#,
    )
    .bind(&source_id)
    .execute(&pool)
    .await
    .unwrap();

    let copied_id = repo
        .copy_chat(
            Owner::User(user_id),
            &source_id,
            CopyChatArgs {
                name: "Copied Chat".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    assert_ne!(source_id, copied_id);

    // Verify the copy has the right name
    let copy = repo.get_metadata(&copied_id).await.unwrap();
    assert_eq!(copy.name, "Copied Chat");

    // Verify the message was copied
    let msg_count: (i64,) =
        sqlx::query_as(r#"SELECT COUNT(*) FROM "ChatMessage" WHERE "chatId" = $1"#)
            .bind(&copied_id)
            .fetch_one(&pool)
            .await
            .unwrap();

    assert_eq!(msg_count.0, 1);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn revert_delete_restores_chat(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();

    let chat_id = repo
        .create(
            Owner::User(user_id),
            CreateChatArgs {
                name: "Revert Me".to_string(),
                project_id: None,
            },
            default_share_permission(),
        )
        .await
        .unwrap();

    repo.delete(&chat_id).await.unwrap();

    // Confirm it's deleted
    let chat = repo.get_metadata(&chat_id).await.unwrap();
    assert!(chat.deleted_at.is_some());

    repo.revert_delete(&chat_id, None).await.unwrap();

    // Confirm it's restored
    let chat = repo.get_metadata(&chat_id).await.unwrap();
    assert!(chat.deleted_at.is_none());

    // Confirm history was re-added
    let count: (i64,) = sqlx::query_as(
        r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,
    )
    .bind(&chat_id)
    .fetch_one(&pool)
    .await
    .unwrap();

    assert_eq!(count.0, 1);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn revert_delete_skips_user_history_for_non_user_owner(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Bot Chat").await;
    insert_owner_principal(&pool, BOT_OWNER, "b1111111-1111-1111-1111-111111111111").await;
    set_chat_owner(&pool, &chat_id, BOT_OWNER).await;
    // `create` recorded history for the creating user; clear it so only
    // `revert_delete` can put rows back.
    sqlx::query(r#"DELETE FROM "UserHistory" WHERE "itemId" = $1"#)
        .bind(&chat_id)
        .execute(&pool)
        .await
        .unwrap();
    repo.delete(&chat_id).await.unwrap();

    repo.revert_delete(&chat_id, None).await.unwrap();

    let chat = repo.get_metadata(&chat_id).await.unwrap();
    assert!(chat.deleted_at.is_none());
    assert_eq!(chat.user_id, Owner::from_principal_str(BOT_OWNER).unwrap());
    assert_eq!(chat_history_count(&pool, &chat_id).await, 0);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_sets_team_share_and_defaults_explicit_null_level_to_view(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Team Chat").await;

    patch_share_permission(
        &repo,
        &chat_id,
        UpdateSharePermissionRequestV2 {
            link_share: Some(Some(LinkShare::Team)),
            link_share_access_level: Some(None),
            team_share_access_level: None,
            channel_share_permissions: None,
        },
    )
    .await;

    let permission = get_stored_share_permission(&pool, &chat_id).await;
    assert_eq!(permission.link_share.as_deref(), Some("TEAM"));
    assert_eq!(permission.link_share_access_level.as_deref(), Some("view"));
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_defaults_explicit_null_level_for_existing_link_share(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Default View Chat").await;

    patch_share_permission(
        &repo,
        &chat_id,
        UpdateSharePermissionRequestV2 {
            link_share: None,
            link_share_access_level: Some(Some(AccessLevel::Edit)),
            team_share_access_level: None,
            channel_share_permissions: None,
        },
    )
    .await;
    patch_share_permission(
        &repo,
        &chat_id,
        UpdateSharePermissionRequestV2 {
            link_share: None,
            link_share_access_level: Some(None),
            team_share_access_level: None,
            channel_share_permissions: None,
        },
    )
    .await;

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

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn patch_chat_disables_link_sharing_and_clears_both_levels(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Private Chat").await;

    patch_share_permission(
        &repo,
        &chat_id,
        UpdateSharePermissionRequestV2 {
            link_share: Some(None),
            link_share_access_level: Some(Some(AccessLevel::Edit)),
            team_share_access_level: None,
            channel_share_permissions: None,
        },
    )
    .await;

    let permission = get_stored_share_permission(&pool, &chat_id).await;
    assert_eq!(permission.link_share, None);
    assert_eq!(permission.link_share_access_level, None);
}

#[sqlx::test(
    migrator = "MACRO_DB_MIGRATIONS",
    fixtures(path = "fixtures", scripts("users"))
)]
async fn get_permissions_reads_link_share_columns(pool: Pool<Postgres>) {
    let repo = test_repo(pool.clone());
    let chat_id = create_test_chat(&repo, "Perms Chat").await;

    let permission = repo.get_permissions(&chat_id).await.unwrap();
    assert_eq!(permission.link_share, Some(LinkShare::Public));
    assert_eq!(permission.link_share_access_level, Some(AccessLevel::View));

    sqlx::query!(
        r#"
        UPDATE "SharePermission" sp
        SET
            "linkShare" = 'TEAM',
            "linkShareAccessLevel" = 'edit'
        FROM "ChatPermission" cp
        WHERE cp."sharePermissionId" = sp.id AND cp."chatId" = $1
        "#,
        &chat_id,
    )
    .execute(&pool)
    .await
    .unwrap();

    let permission = repo.get_permissions(&chat_id).await.unwrap();

    assert!(!permission.id.is_empty());
    assert_eq!(permission.owner, "macro|[email protected]");
    assert_eq!(permission.link_share, Some(LinkShare::Team));
    assert_eq!(permission.link_share_access_level, Some(AccessLevel::Edit));
}