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.

94.5 KB
Raw Blame
//! Unit tests for the EntityAccessService.

#[allow(unused_imports)]
use super::*;

mod call_session;
use crate::domain::models::{
    AdminParticipantRole, AdminTeamRole, AnyEntityPermission, BotAccessScope, BotId,
    BotReceiptScope, CallChannelInfo, CommentAccessLevel, EditAccessLevel, EntityAccessAuth,
    MemberParticipantRole, MemberTeamRole, OwnerParticipantRole, ParticipantRole, UserTeamInfo,
    ViewAccessLevel, ViewOnly,
};
use crate::domain::ports::{AccessibleForms, ScheduledActionGrants};
use macro_user_id::user_id::MacroUserIdStr;
use models_permissions::share_permission::access_level::OwnerAccessLevel;
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};
use tokio::sync::Mutex;

/// Mock repository for testing.
#[derive(Clone)]
struct MockRepo {
    document_access: Arc<Mutex<Option<AccessLevel>>>,
    chat_access: Arc<Mutex<Option<AccessLevel>>>,
    project_access: Arc<Mutex<Option<AccessLevel>>>,
    thread_access: Arc<Mutex<Option<AccessLevel>>>,
    calendar_event_access: Arc<Mutex<Option<AccessLevel>>>,
    thread_access_calls: Arc<AtomicUsize>,
    owned_email_thread_ids: Arc<Mutex<Vec<Uuid>>>,
    call_access: Arc<Mutex<Option<AccessLevel>>>,
    agent_session_access: Arc<Mutex<Option<AccessLevel>>>,
    initiative_access: Arc<Mutex<Option<AccessLevel>>>,
    scheduled_action_access: Arc<Mutex<Option<AccessLevel>>>,
    accessible_scheduled_action_ids: Arc<Mutex<Vec<Uuid>>>,
    agent_session_parent: Arc<Mutex<Option<AgentSessionParent>>>,
    agent_session_exists: Arc<Mutex<bool>>,
    pipeline_access: Arc<Mutex<Option<AccessLevel>>>,
    pipeline_access_list: Arc<Mutex<Vec<(Uuid, AccessLevel)>>>,
    database_access: Arc<Mutex<Option<AccessLevel>>>,
    database_access_list: Arc<Mutex<Vec<(Uuid, AccessLevel)>>>,
    database_row_access: Arc<Mutex<Option<AccessLevel>>>,
    database_row_access_calls: Arc<AtomicUsize>,
    form_access: Arc<Mutex<Option<AccessLevel>>>,
    form_access_callers: Arc<Mutex<Vec<Option<String>>>>,
    form_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    form_access_list: Arc<Mutex<Vec<(Uuid, AccessLevel)>>>,
    external_chat_access: Arc<Mutex<Option<AccessLevel>>>,
    external_chat_access_callers: Arc<Mutex<Vec<Option<String>>>>,
    reminder_access: Arc<Mutex<Option<AccessLevel>>>,
    team_entity_access: Arc<Mutex<Option<AccessLevel>>>,
    team_agent_session_access: Arc<Mutex<Option<AccessLevel>>>,
    team_entity_requests: Arc<Mutex<Vec<(String, EntityType)>>>,
    team_entity_access_calls: Arc<AtomicUsize>,
    team_channel_role: Arc<Mutex<ChannelRoleResult>>,
    team_channel_role_calls: Arc<AtomicUsize>,
    foreign_entity_access: Arc<Mutex<bool>>,
    team_foreign_entity_access: Arc<Mutex<bool>>,
    crm_company_access: Arc<Mutex<Option<AccessLevel>>>,
    crm_contact_access: Arc<Mutex<Option<AccessLevel>>>,
    team_crm_company_access: Arc<Mutex<Option<CrmEntityAccess>>>,
    team_crm_contact_access: Arc<Mutex<Option<CrmEntityAccess>>>,
    channel_membership: Arc<Mutex<Vec<Uuid>>>,
    channel_role: Arc<Mutex<ChannelRoleResult>>,
    last_channel_role_request: Arc<Mutex<Option<(String, Option<i64>)>>>,
    document_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    chat_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    project_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    thread_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    agent_session_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    database_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    database_row_database: Arc<Mutex<Option<Uuid>>>,
    channel_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    call_channel: Arc<Mutex<Option<CallChannelInfo>>>,
    call_users: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
    user_team: Arc<Mutex<Option<UserTeamInfo>>>,
}

impl MockRepo {
    fn new() -> Self {
        Self {
            document_access: Arc::new(Mutex::new(None)),
            chat_access: Arc::new(Mutex::new(None)),
            project_access: Arc::new(Mutex::new(None)),
            thread_access: Arc::new(Mutex::new(None)),
            calendar_event_access: Arc::new(Mutex::new(None)),
            thread_access_calls: Arc::new(AtomicUsize::new(0)),
            owned_email_thread_ids: Arc::new(Mutex::new(Vec::new())),
            call_access: Arc::new(Mutex::new(None)),
            agent_session_access: Arc::new(Mutex::new(None)),
            initiative_access: Arc::new(Mutex::new(None)),
            scheduled_action_access: Arc::new(Mutex::new(None)),
            accessible_scheduled_action_ids: Arc::new(Mutex::new(Vec::new())),
            agent_session_parent: Arc::default(),
            // Existing by default: the interesting half of these tests is who
            // may see a session, not whether it is there.
            agent_session_exists: Arc::new(Mutex::new(true)),
            pipeline_access: Arc::default(),
            pipeline_access_list: Arc::default(),
            database_access: Arc::new(Mutex::new(None)),
            database_access_list: Arc::new(Mutex::new(Vec::new())),
            database_row_access: Arc::new(Mutex::new(None)),
            database_row_access_calls: Arc::default(),
            form_access: Arc::default(),
            form_access_callers: Arc::default(),
            form_users: Arc::default(),
            form_access_list: Arc::default(),
            external_chat_access: Arc::default(),
            external_chat_access_callers: Arc::default(),
            reminder_access: Arc::new(Mutex::new(None)),
            team_entity_access: Arc::new(Mutex::new(None)),
            team_agent_session_access: Arc::default(),
            team_entity_requests: Arc::default(),
            team_entity_access_calls: Arc::new(AtomicUsize::new(0)),
            team_channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
            team_channel_role_calls: Arc::new(AtomicUsize::new(0)),
            foreign_entity_access: Arc::new(Mutex::new(false)),
            team_foreign_entity_access: Arc::new(Mutex::new(false)),
            crm_company_access: Arc::new(Mutex::new(None)),
            crm_contact_access: Arc::new(Mutex::new(None)),
            team_crm_company_access: Arc::new(Mutex::new(None)),
            team_crm_contact_access: Arc::new(Mutex::new(None)),
            channel_membership: Arc::new(Mutex::new(vec![])),
            channel_role: Arc::new(Mutex::new(ChannelRoleResult::NotFound)),
            last_channel_role_request: Arc::new(Mutex::new(None)),
            document_users: Arc::new(Mutex::new(vec![])),
            chat_users: Arc::new(Mutex::new(vec![])),
            project_users: Arc::new(Mutex::new(vec![])),
            thread_users: Arc::new(Mutex::new(vec![])),
            agent_session_users: Arc::new(Mutex::new(Vec::new())),
            database_users: Arc::new(Mutex::new(vec![])),
            database_row_database: Arc::default(),
            channel_users: Arc::new(Mutex::new(vec![])),
            call_channel: Arc::new(Mutex::new(None)),
            call_users: Arc::default(),
            user_team: Arc::new(Mutex::new(None)),
        }
    }

    fn with_document_access(mut self, level: AccessLevel) -> Self {
        self.document_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_chat_access(mut self, level: AccessLevel) -> Self {
        self.chat_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_project_access(mut self, level: AccessLevel) -> Self {
        self.project_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_thread_access(mut self, level: AccessLevel) -> Self {
        self.thread_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_owned_email_thread_ids(mut self, ids: Vec<Uuid>) -> Self {
        self.owned_email_thread_ids = Arc::new(Mutex::new(ids));
        self
    }

    #[allow(dead_code)]
    fn with_call_access(mut self, level: AccessLevel) -> Self {
        self.call_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_reminder_access(mut self, level: AccessLevel) -> Self {
        self.reminder_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_agent_session_access(mut self, level: AccessLevel) -> Self {
        self.agent_session_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    /// No session row under the asked-for id: never created, or deleted since.
    fn without_agent_session_row(mut self) -> Self {
        self.agent_session_exists = Arc::new(Mutex::new(false));
        self
    }

    fn with_database_access(mut self, level: AccessLevel) -> Self {
        self.database_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_database_access_list(mut self, levels: Vec<(Uuid, AccessLevel)>) -> Self {
        self.database_access_list = Arc::new(Mutex::new(levels));
        self
    }

    fn with_form_access(mut self, level: AccessLevel) -> Self {
        self.form_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_external_chat_access(mut self, level: AccessLevel) -> Self {
        self.external_chat_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_form_access_list(mut self, levels: Vec<(Uuid, AccessLevel)>) -> Self {
        self.form_access_list = Arc::new(Mutex::new(levels));
        self
    }

    fn with_form_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.form_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_database_row_access(mut self, level: AccessLevel) -> Self {
        self.database_row_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_scheduled_action_access(mut self, level: AccessLevel) -> Self {
        self.scheduled_action_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_accessible_scheduled_action_ids(mut self, ids: Vec<Uuid>) -> Self {
        self.accessible_scheduled_action_ids = Arc::new(Mutex::new(ids));
        self
    }

    fn with_team_entity_access(mut self, level: AccessLevel) -> Self {
        self.team_entity_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_team_channel_role(mut self, result: ChannelRoleResult) -> Self {
        self.team_channel_role = Arc::new(Mutex::new(result));
        self
    }

    fn team_repository_calls(&self) -> usize {
        self.team_entity_access_calls.load(Ordering::SeqCst)
            + self.team_channel_role_calls.load(Ordering::SeqCst)
    }

    fn with_foreign_entity_access(mut self, has_access: bool) -> Self {
        self.foreign_entity_access = Arc::new(Mutex::new(has_access));
        self
    }

    fn with_team_foreign_entity_access(mut self, has_access: bool) -> Self {
        self.team_foreign_entity_access = Arc::new(Mutex::new(has_access));
        self
    }

    #[allow(dead_code)]
    fn with_crm_company_access(mut self, level: AccessLevel) -> Self {
        self.crm_company_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    #[allow(dead_code)]
    fn with_crm_contact_access(mut self, level: AccessLevel) -> Self {
        self.crm_contact_access = Arc::new(Mutex::new(Some(level)));
        self
    }

    fn with_team_crm_company_access(mut self, access: CrmEntityAccess) -> Self {
        self.team_crm_company_access = Arc::new(Mutex::new(Some(access)));
        self
    }

    fn with_team_crm_contact_access(mut self, access: CrmEntityAccess) -> Self {
        self.team_crm_contact_access = Arc::new(Mutex::new(Some(access)));
        self
    }

    fn with_channel_membership(mut self, channels: Vec<Uuid>) -> Self {
        self.channel_membership = Arc::new(Mutex::new(channels));
        self
    }

    fn with_channel_role(mut self, result: ChannelRoleResult) -> Self {
        self.channel_role = Arc::new(Mutex::new(result));
        self
    }

    fn with_document_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.document_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_database_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.database_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_database_row_database(mut self, database_id: Uuid) -> Self {
        self.database_row_database = Arc::new(Mutex::new(Some(database_id)));
        self
    }

    fn with_chat_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.chat_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_project_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.project_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_thread_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.thread_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_agent_session_users(mut self, users: Vec<MacroUserIdStr<'static>>) -> Self {
        self.agent_session_users = Arc::new(Mutex::new(users));
        self
    }

    fn with_user_team(mut self, user_team: UserTeamInfo) -> Self {
        self.user_team = Arc::new(Mutex::new(Some(user_team)));
        self
    }
}

impl AccessRepository for MockRepo {
    async fn get_agent_session_parent(
        &self,
        _: &str,
    ) -> Result<Option<AgentSessionParent>, AccessError> {
        Ok(self.agent_session_parent.lock().await.clone())
    }

    async fn agent_session_exists(&self, _: &str) -> Result<bool, AccessError> {
        Ok(*self.agent_session_exists.lock().await)
    }

    async fn get_document_access(
        &self,
        _document_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.document_access.lock().await)
    }

    async fn get_chat_access(
        &self,
        _chat_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.chat_access.lock().await)
    }

    async fn get_project_access(
        &self,
        _project_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.project_access.lock().await)
    }

    async fn get_thread_access(
        &self,
        _thread_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        self.thread_access_calls.fetch_add(1, Ordering::SeqCst);
        Ok(*self.thread_access.lock().await)
    }

    async fn get_calendar_event_access(
        &self,
        _event_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.calendar_event_access.lock().await)
    }

    async fn get_owned_email_thread_ids(
        &self,
        thread_ids: &[Uuid],
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<Vec<Uuid>, AccessError> {
        let owned = self.owned_email_thread_ids.lock().await;
        Ok(thread_ids
            .iter()
            .copied()
            .filter(|id| owned.contains(id))
            .collect())
    }

    async fn check_user_channel_membership(
        &self,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
        _channel_ids: &[Uuid],
    ) -> Result<Vec<Uuid>, AccessError> {
        Ok(self.channel_membership.lock().await.clone())
    }

    async fn get_channel_role(
        &self,
        _channel_id: &Uuid,
        user_id: Option<&MacroUserId<Lowercase<'_>>>,
        user_org_id: Option<i64>,
    ) -> Result<ChannelRoleResult, AccessError> {
        *self.last_channel_role_request.lock().await = Some((
            user_id.map(AsRef::as_ref).unwrap_or_default().to_string(),
            user_org_id,
        ));
        Ok(*self.channel_role.lock().await)
    }

    async fn get_call_access(
        &self,
        _call_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.call_access.lock().await)
    }

    async fn get_agent_session_access(
        &self,
        _agent_session_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.agent_session_access.lock().await)
    }

    async fn get_initiative_access(
        &self,
        _initiative_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.initiative_access.lock().await)
    }

    async fn get_pipeline_access(
        &self,
        _id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.pipeline_access.lock().await)
    }
    async fn list_pipeline_access(
        &self,
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<Vec<(Uuid, AccessLevel)>, AccessError> {
        Ok(self.pipeline_access_list.lock().await.clone())
    }

    async fn get_database_access(
        &self,
        _database_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.database_access.lock().await)
    }

    async fn list_database_access(
        &self,
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<Vec<(Uuid, AccessLevel)>, AccessError> {
        Ok(self.database_access_list.lock().await.clone())
    }

    async fn get_form_access(
        &self,
        _form_id: &str,
        user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        self.form_access_callers
            .lock()
            .await
            .push(user_id.map(|user_id| user_id.as_ref().to_string()));
        Ok(*self.form_access.lock().await)
    }

    /// Resolve ordinary shares on an external chat.
    async fn get_external_chat_access(
        &self,
        _group_id: &str,
        user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        self.external_chat_access_callers
            .lock()
            .await
            .push(user_id.map(|user_id| user_id.as_ref().to_string()));
        Ok(*self.external_chat_access.lock().await)
    }

    async fn list_form_access(
        &self,
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<Vec<(Uuid, AccessLevel)>, AccessError> {
        Ok(self.form_access_list.lock().await.clone())
    }

    async fn get_database_row_access(
        &self,
        _row_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        self.database_row_access_calls
            .fetch_add(1, Ordering::SeqCst);
        Ok(*self.database_row_access.lock().await)
    }

    async fn get_database_rows_access(
        &self,
        row_ids: &[Uuid],
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<HashMap<Uuid, AccessLevel>, AccessError> {
        self.database_row_access_calls
            .fetch_add(1, Ordering::SeqCst);
        let level = *self.database_row_access.lock().await;
        Ok(row_ids
            .iter()
            .filter_map(|id| level.map(|level| (*id, level)))
            .collect())
    }

    async fn get_scheduled_action_access(
        &self,
        _scheduled_action_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.scheduled_action_access.lock().await)
    }

    async fn accessible_scheduled_action_ids(
        &self,
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<Vec<Uuid>, AccessError> {
        Ok(self.accessible_scheduled_action_ids.lock().await.clone())
    }

    async fn get_reminder_access(
        &self,
        _reminder_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<AccessLevel>, AccessError> {
        Ok(*self.reminder_access.lock().await)
    }

    async fn get_team_entity_access(
        &self,
        _bot_id: BotId,
        _team_id: Uuid,
        entity_id: &str,
        entity_type: EntityType,
    ) -> Result<Option<AccessLevel>, AccessError> {
        self.team_entity_access_calls.fetch_add(1, Ordering::SeqCst);
        self.team_entity_requests
            .lock()
            .await
            .push((entity_id.into(), entity_type));
        if entity_type == EntityType::AgentSession {
            return Ok(*self.team_agent_session_access.lock().await);
        }
        Ok(*self.team_entity_access.lock().await)
    }

    async fn get_team_channel_role(
        &self,
        _channel_id: &Uuid,
        _team_id: Uuid,
        _bot_id: BotId,
    ) -> Result<ChannelRoleResult, AccessError> {
        self.team_channel_role_calls.fetch_add(1, Ordering::SeqCst);
        Ok(*self.team_channel_role.lock().await)
    }

    async fn has_team_foreign_entity_access(
        &self,
        _foreign_entity_id: &str,
        _team_id: Uuid,
        _bot_id: BotId,
    ) -> Result<bool, AccessError> {
        Ok(*self.team_foreign_entity_access.lock().await)
    }

    async fn get_team_crm_company_access(
        &self,
        _company_id: &str,
        _team_id: Uuid,
    ) -> Result<Option<CrmEntityAccess>, AccessError> {
        Ok(*self.team_crm_company_access.lock().await)
    }

    async fn get_team_crm_contact_access(
        &self,
        _contact_id: &str,
        _team_id: Uuid,
    ) -> Result<Option<CrmEntityAccess>, AccessError> {
        Ok(*self.team_crm_contact_access.lock().await)
    }

    async fn has_foreign_entity_access(
        &self,
        _foreign_entity_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<bool, AccessError> {
        Ok(*self.foreign_entity_access.lock().await)
    }

    async fn get_crm_company_access(
        &self,
        _company_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<CrmEntityAccess>, AccessError> {
        // Owning team / role are irrelevant to these access-level tests.
        Ok(
            (*self.crm_company_access.lock().await).map(|access_level| CrmEntityAccess {
                access_level,
                team_id: Uuid::nil(),
                team_role: TeamRole::Member,
            }),
        )
    }

    async fn get_crm_contact_access(
        &self,
        _contact_id: &str,
        _user_id: Option<&MacroUserId<Lowercase<'_>>>,
    ) -> Result<Option<CrmEntityAccess>, AccessError> {
        // Owning team / role are irrelevant to these access-level tests.
        Ok(
            (*self.crm_contact_access.lock().await).map(|access_level| CrmEntityAccess {
                access_level,
                team_id: Uuid::nil(),
                team_role: TeamRole::Member,
            }),
        )
    }

    async fn get_entity_users(
        &self,
        _entity_id: &uuid::Uuid,
        entity_type: EntityType,
    ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
        match entity_type {
            EntityType::Document => Ok(self.document_users.lock().await.clone()),
            EntityType::Chat => Ok(self.chat_users.lock().await.clone()),
            EntityType::Project => Ok(self.project_users.lock().await.clone()),
            EntityType::EmailThread => Ok(self.thread_users.lock().await.clone()),
            EntityType::AgentSession => Ok(self.agent_session_users.lock().await.clone()),
            EntityType::Call => panic!("standalone calls must use direct grants"),
            EntityType::Initiative => Ok(vec![]),
            EntityType::Database => Ok(self.database_users.lock().await.clone()),
            EntityType::Form => Ok(self.form_users.lock().await.clone()),
            _ => Err(AccessError::BadRequest("unsupported entity type")),
        }
    }

    async fn get_direct_entity_users(
        &self,
        _entity_id: &Uuid,
        entity_type: EntityType,
    ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
        assert_eq!(entity_type, EntityType::Call);
        Ok(self.call_users.lock().await.clone())
    }

    async fn get_channel_users(
        &self,
        _channel_id: &Uuid,
    ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {
        Ok(self.channel_users.lock().await.clone())
    }

    async fn get_call_channel(
        &self,
        _call_id: &Uuid,
    ) -> Result<Option<CallChannelInfo>, AccessError> {
        Ok(self.call_channel.lock().await.clone())
    }

    async fn get_database_row_database(&self, _row_id: &Uuid) -> Result<Option<Uuid>, AccessError> {
        Ok(*self.database_row_database.lock().await)
    }

    async fn get_call_channel_by_channel_id(
        &self,
        _channel_id: &Uuid,
    ) -> Result<Option<CallChannelInfo>, AccessError> {
        Ok(self.call_channel.lock().await.clone())
    }

    async fn get_user_team(
        &self,
        _user_id: &MacroUserId<Lowercase<'_>>,
    ) -> Result<Option<UserTeamInfo>, AccessError> {
        Ok(*self.user_team.lock().await)
    }
}

fn test_user_id() -> MacroUserIdStr<'static> {
    MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()
}

fn test_bot_id() -> BotId {
    BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"))
}

fn test_team_id() -> Uuid {
    uuid::uuid!("00000000-0000-0000-0000-000000000456")
}

fn test_bot_scope() -> BotAccessScope {
    BotAccessScope::Team {
        team_id: test_team_id(),
    }
}

fn test_user_bot_scope(user_org_id: Option<i64>) -> BotAccessScope {
    BotAccessScope::User {
        user_id: test_user_id(),
        user_org_id,
    }
}

fn user_id(s: &str) -> MacroUserIdStr<'static> {
    MacroUserIdStr::try_from(s.to_string()).unwrap()
}

const FOREIGN_ENTITY_ID: &str = "22222222-2222-2222-2222-222222222222";

#[tokio::test]
async fn test_get_document_access_returns_level_from_repo() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), "doc-1", EntityType::Document)
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::Edit));
}

#[tokio::test]
async fn test_get_chat_access_returns_level_from_repo() {
    let repo = MockRepo::new().with_chat_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), "chat-1", EntityType::Chat)
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::View));
}

#[tokio::test]
async fn test_get_project_access_returns_level_from_repo() {
    let repo = MockRepo::new().with_project_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), "proj-1", EntityType::Project)
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::Owner));
}

#[tokio::test]
async fn test_get_thread_access_returns_level_from_repo() {
    let repo = MockRepo::new().with_thread_access(AccessLevel::Comment);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), "thread-1", EntityType::EmailThread)
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::Comment));
}

#[tokio::test]
async fn test_get_channel_access_for_member_returns_view() {
    let channel_uuid: Uuid = "11111111-1111-1111-1111-111111111111".parse().unwrap();
    let repo = MockRepo::new().with_channel_membership(vec![channel_uuid]);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::View));
}

#[tokio::test]
async fn test_get_channel_access_for_non_member_returns_none() {
    let repo = MockRepo::new().with_channel_membership(vec![]);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await;

    assert_eq!(result.unwrap(), None);
}

#[tokio::test]
async fn test_get_channel_access_with_invalid_uuid_returns_error() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), "not-a-uuid", EntityType::Channel)
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

#[tokio::test]
async fn test_get_foreign_entity_access_returns_view_when_repo_grants_access() {
    let repo = MockRepo::new().with_foreign_entity_access(true);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), FOREIGN_ENTITY_ID, EntityType::ForeignEntity)
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::View));
}

#[tokio::test]
async fn test_get_foreign_entity_access_returns_none_when_repo_denies_access() {
    let repo = MockRepo::new().with_foreign_entity_access(false);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(Some(&user_id), FOREIGN_ENTITY_ID, EntityType::ForeignEntity)
        .await;

    assert_eq!(result.unwrap(), None);
}

#[tokio::test]
async fn test_check_access_sufficient_level_returns_actual_level() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .check_access(
            Some(&user_id),
            "doc-1",
            EntityType::Document,
            AccessLevel::View,
        )
        .await;

    assert_eq!(result.unwrap(), AccessLevel::Edit);
}

#[tokio::test]
async fn test_check_access_insufficient_level_returns_unauthorized() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .check_access(
            Some(&user_id),
            "doc-1",
            EntityType::Document,
            AccessLevel::Edit,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_check_access_no_access_returns_unauthorized() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .check_access(
            Some(&user_id),
            "doc-1",
            EntityType::Document,
            AccessLevel::View,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_unsupported_entity_type_returns_none() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    // Team, and User entity types don't have access checks implemented
    let result = service
        .get_access_level(Some(&user_id), "team-1", EntityType::Team)
        .await;
    assert_eq!(result.unwrap(), None);

    let result = service
        .get_access_level(Some(&user_id), "user-1", EntityType::User)
        .await;
    assert_eq!(result.unwrap(), None);
}

// --- get_entity_permission tests ---

#[tokio::test]
async fn team_admin_receipt_checks_current_role_and_exact_team() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo.clone());
    let user = test_user_id();
    let team = Uuid::now_v7();
    let team_id = team.to_string();
    for role in [TeamRole::Owner, TeamRole::Admin, TeamRole::Member] {
        *repo.user_team.lock().await = Some(UserTeamInfo {
            team_id: team,
            role,
        });
        let receipt = service
            .generate_entity_access_receipt::<AdminTeamRole>(
                &user.0,
                None,
                &team_id,
                EntityType::Team,
            )
            .await;
        assert_eq!(receipt.is_ok(), role != TeamRole::Member);
        assert!(
            service
                .generate_entity_access_receipt::<AdminTeamRole>(
                    &user.0,
                    None,
                    &Uuid::now_v7().to_string(),
                    EntityType::Team,
                )
                .await
                .is_err()
        );
    }
    *repo.user_team.lock().await = None;
    assert!(
        service
            .generate_entity_access_receipt::<AdminTeamRole>(
                &user.0,
                None,
                &team_id,
                EntityType::Team,
            )
            .await
            .is_err()
    );
    assert!(
        service
            .get_entity_permission(None, &team_id, EntityType::Team, None)
            .await
            .is_err()
    );
}

#[tokio::test]
async fn test_get_entity_permission_document_returns_access_level() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(Some(&user_id), "doc-1", EntityType::Document, None)
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    ));
}

#[tokio::test]
async fn test_get_entity_permission_document_no_access_returns_unauthorized() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(Some(&user_id), "doc-1", EntityType::Document, None)
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_get_entity_permission_agent_session_returns_access_level() {
    let repo = MockRepo::new().with_agent_session_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb0",
            EntityType::AgentSession,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
}

/// A session that is there, held by someone else: a refusal, and the caller
/// is told to stop asking.
#[tokio::test]
async fn test_get_entity_permission_agent_session_no_access_returns_unauthorized() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb0",
            EntityType::AgentSession,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

/// No row under that id - never created, or deleted since. Answered apart
/// from a refusal so a client reading a session whose create has not landed
/// can tell "not yet" from "not yours" and try again.
#[tokio::test]
async fn test_get_entity_permission_agent_session_missing_row_returns_not_found() {
    let service = EntityAccessServiceImpl::new(MockRepo::new().without_agent_session_row());
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb0",
            EntityType::AgentSession,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::NotFound(_))));
}

/// Existence is a cost only a refusal pays: a granted read must not spend a
/// round trip proving what the grant already implies.
#[tokio::test]
async fn test_get_entity_permission_agent_session_with_access_skips_existence_check() {
    let repo = MockRepo::new()
        .with_agent_session_access(AccessLevel::Owner)
        .without_agent_session_row();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb0",
            EntityType::AgentSession,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
}

#[tokio::test]
async fn test_get_entity_permission_database_returns_access_level() {
    let repo = MockRepo::new().with_database_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb0",
            EntityType::Database,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
}

#[tokio::test]
async fn accessible_databases_are_the_repository_listing() {
    let shared = Uuid::parse_str("0198a805-3e22-75b2-97eb-d9c6b91accb0").unwrap();
    let owned = Uuid::parse_str("0198a805-3e22-75b2-97eb-d9c6b91accb1").unwrap();
    let repo = MockRepo::new().with_database_access_list(vec![
        (shared, AccessLevel::View),
        (owned, AccessLevel::Owner),
    ]);
    let service = EntityAccessServiceImpl::new(repo);

    assert_eq!(
        service.accessible_databases(&test_user_id()).await.unwrap(),
        vec![(shared, AccessLevel::View), (owned, AccessLevel::Owner)]
    );
}

#[tokio::test]
async fn test_get_entity_permission_database_no_access_returns_unauthorized() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb0",
            EntityType::Database,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_get_entity_permission_database_row_resolves_through_its_database() {
    let repo = MockRepo::new().with_database_row_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb1",
            EntityType::DatabaseRow,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    ));
}

#[tokio::test]
async fn test_get_access_level_database_row_uses_the_row_query_not_the_database_query() {
    let repo = MockRepo::new().with_database_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(
            Some(&user_id),
            "0198a805-3e22-75b2-97eb-d9c6b91accb1",
            EntityType::DatabaseRow,
        )
        .await
        .unwrap();

    assert_eq!(result, None);
}

#[tokio::test]
async fn test_get_access_level_scheduled_action_returns_scripted_level() {
    let repo = MockRepo::new().with_scheduled_action_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_access_level(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::ScheduledAction,
        )
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::Edit));
}

#[tokio::test]
async fn test_get_entity_permission_scheduled_action_returns_scripted_level() {
    let repo = MockRepo::new().with_scheduled_action_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::ScheduledAction,
            None,
        )
        .await
        .unwrap();

    assert_eq!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    );
}

#[tokio::test]
async fn test_get_entity_permission_scheduled_action_without_grant_is_unauthorized() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::ScheduledAction,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_accessible_scheduled_action_ids_passes_through() {
    let id = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_5a01);
    let repo = MockRepo::new().with_accessible_scheduled_action_ids(vec![id]);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let ids = service
        .accessible_scheduled_action_ids(&user_id)
        .await
        .unwrap();

    assert_eq!(ids, vec![id]);
}

#[tokio::test]
async fn test_get_entity_permission_foreign_entity_returns_view_access_level() {
    let repo = MockRepo::new().with_foreign_entity_access(true);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            FOREIGN_ENTITY_ID,
            EntityType::ForeignEntity,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View
        }
    ));
}

/// Reminders reach `get_entity_permission` from AI tools, which mint their own
/// receipts rather than going through `ReminderAccessExtractor`.
#[tokio::test]
async fn test_get_entity_permission_reminder_returns_owner() {
    let repo = MockRepo::new().with_reminder_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Reminder,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
}

/// Somebody else's reminder and a reminder that does not exist are the same
/// answer, which is what keeps an id from leaking.
#[tokio::test]
async fn test_get_entity_permission_reminder_not_owned_is_unauthorized() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Reminder,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

/// The receipt an AI tool actually asks for. `OwnerAccessLevel` is the only
/// requirement a reminder can satisfy, so this is the whole gate.
#[tokio::test]
async fn test_generate_reminder_owner_receipt() {
    let repo = MockRepo::new().with_reminder_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<OwnerAccessLevel>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Reminder,
        )
        .await
        .expect("owner should get a receipt");

    assert_eq!(receipt.entity().entity_type, EntityType::Reminder);
    assert_eq!(
        receipt.entity().entity_id,
        "11111111-1111-1111-1111-111111111111"
    );
    assert_eq!(
        receipt
            .get_authenticated_user()
            .expect("receipt is authenticated")
            .as_ref(),
        user_id.as_ref()
    );
}

#[tokio::test]
async fn test_get_entity_permission_channel_returns_role() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(
        result,
        EntityPermission::ChannelRole {
            role: ParticipantRole::Admin
        }
    ));
}

#[tokio::test]
async fn test_get_entity_permission_channel_returns_view_only() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::ViewOnly);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
            None,
        )
        .await
        .unwrap();

    assert!(matches!(result, EntityPermission::ChannelViewOnly));
}

#[tokio::test]
async fn test_get_entity_permission_channel_no_access_returns_unauthorized() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NoAccess);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_get_entity_permission_channel_not_found_returns_not_found() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NotFound);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
            None,
        )
        .await;

    assert!(matches!(result, Err(AccessError::NotFound(_))));
}

#[tokio::test]
async fn test_get_entity_permission_invalid_channel_uuid_returns_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(Some(&user_id), "not-a-uuid", EntityType::Channel, None)
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

#[tokio::test]
async fn test_get_entity_permission_unsupported_type_returns_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(Some(&user_id), "team-1", EntityType::Team, None)
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

// --- Public (unauthenticated) access tests ---

#[tokio::test]
async fn test_public_access_with_sufficient_level_returns_level() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .check_public_access("doc-1", EntityType::Document, AccessLevel::View)
        .await;

    assert_eq!(result.unwrap(), AccessLevel::View);
}

#[tokio::test]
async fn test_public_access_with_insufficient_level_returns_unauthorized() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .check_public_access("doc-1", EntityType::Document, AccessLevel::Edit)
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_public_access_with_no_access_returns_unauthorized() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .check_public_access("doc-1", EntityType::Document, AccessLevel::View)
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_get_access_level_with_none_user_id() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_access_level(None, "doc-1", EntityType::Document)
        .await;

    assert_eq!(result.unwrap(), Some(AccessLevel::View));
}

#[tokio::test]
async fn test_check_access_with_none_user_id_and_sufficient_level() {
    let repo = MockRepo::new().with_project_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .check_access(None, "proj-1", EntityType::Project, AccessLevel::View)
        .await;

    assert_eq!(result.unwrap(), AccessLevel::View);
}

#[tokio::test]
async fn test_check_access_with_none_user_id_and_no_access() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .check_access(None, "doc-1", EntityType::Document, AccessLevel::View)
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

// --- generate_entity_access_receipt tests ---

#[tokio::test]
async fn test_batch_email_receipts_use_owned_thread_fast_path() {
    let thread_id = Uuid::new_v4();
    let repo = MockRepo::new().with_owned_email_thread_ids(vec![thread_id]);
    let calls = repo.thread_access_calls.clone();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let mut receipts = service
        .generate_email_thread_view_access_receipts(&user_id, None, &[thread_id.to_string()])
        .await;
    let receipt = receipts.remove(&thread_id.to_string()).unwrap().unwrap();

    assert_eq!(calls.load(Ordering::SeqCst), 0);
    assert_eq!(receipt.entity().entity_type, EntityType::EmailThread);
    assert_eq!(receipt.entity().entity_id, thread_id.to_string());
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
}

#[tokio::test]
async fn test_batch_email_receipts_fall_back_for_shared_threads() {
    let thread_id = Uuid::new_v4();
    let repo = MockRepo::new().with_thread_access(AccessLevel::View);
    let calls = repo.thread_access_calls.clone();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipts = service
        .generate_email_thread_view_access_receipts(&user_id, None, &[thread_id.to_string()])
        .await;

    assert_eq!(calls.load(Ordering::SeqCst), 1);
    assert!(receipts[&thread_id.to_string()].is_ok());
}

#[tokio::test]
async fn test_generate_receipt_document_with_access() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<ViewAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await
        .unwrap();

    assert!(matches!(receipt.auth(), EntityAccessAuth::Authenticated(_)));
    assert_eq!(receipt.entity().entity_id, "doc-1");
    assert!(matches!(receipt.entity().entity_type, EntityType::Document));
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_document_no_access_returns_unauthorized() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<ViewAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn user_scoped_bot_delegates_to_the_acting_user() {
    let bot_id = test_bot_id();
    let scope = test_user_bot_scope(Some(42));
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo.clone());

    let receipt = service
        .generate_bot_entity_access_receipt::<ViewAccessLevel>(
            bot_id,
            scope.clone(),
            "doc-1",
            EntityType::Document,
        )
        .await
        .unwrap();

    assert!(matches!(receipt.auth(), EntityAccessAuth::Bot(id) if id.bot_id() == bot_id));
    assert_eq!(
        receipt.get_authenticated_bot_auth().unwrap().scope(),
        &BotReceiptScope::from(&scope)
    );
    assert_eq!(receipt.acting_user_id(), Some(&test_user_id()));
    assert!(matches!(
        receipt.get_authenticated_user(),
        Err(AccessError::Unauthorized)
    ));
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    ));
    assert_eq!(repo.team_repository_calls(), 0);
}

#[tokio::test]
async fn user_scoped_bot_preserves_the_acting_users_organization() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
    let request = repo.last_channel_role_request.clone();
    let service = EntityAccessServiceImpl::new(repo);

    service
        .generate_bot_entity_access_receipt::<MemberParticipantRole>(
            test_bot_id(),
            test_user_bot_scope(Some(42)),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await
        .unwrap();

    assert_eq!(
        *request.lock().await,
        Some((test_user_id().to_string(), Some(42)))
    );
}

#[tokio::test]
async fn user_scoped_bot_receives_the_acting_users_role_on_their_team() {
    let team_id = test_team_id();
    let repo = MockRepo::new().with_user_team(UserTeamInfo {
        team_id,
        role: TeamRole::Admin,
    });
    let service = EntityAccessServiceImpl::new(repo);

    let receipt = service
        .generate_bot_entity_access_receipt::<AdminTeamRole>(
            test_bot_id(),
            test_user_bot_scope(None),
            &team_id.to_string(),
            EntityType::Team,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::TeamRole {
            role: TeamRole::Admin
        }
    ));
}

#[tokio::test]
async fn user_scoped_bot_cannot_access_another_team() {
    let repo = MockRepo::new().with_user_team(UserTeamInfo {
        team_id: test_team_id(),
        role: TeamRole::Owner,
    });
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .generate_bot_entity_access_receipt::<MemberTeamRole>(
            test_bot_id(),
            test_user_bot_scope(None),
            &Uuid::new_v4().to_string(),
            EntityType::Team,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn team_scoped_bot_dispatches_all_item_types() {
    let repo = MockRepo::new().with_team_entity_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo.clone());

    for entity_type in [
        EntityType::Document,
        EntityType::Chat,
        EntityType::Project,
        EntityType::EmailThread,
        EntityType::Call,
        EntityType::Initiative,
        EntityType::DatabaseRow,
    ] {
        let receipt = service
            .generate_bot_entity_access_receipt::<ViewAccessLevel>(
                test_bot_id(),
                test_bot_scope(),
                &Uuid::new_v4().to_string(),
                entity_type,
            )
            .await
            .unwrap();

        assert_eq!(
            receipt.get_authenticated_bot_auth().unwrap().scope(),
            &BotReceiptScope::from(&test_bot_scope())
        );
        assert!(matches!(
            receipt.entity_permission(),
            EntityPermission::AccessLevel {
                access_level: AccessLevel::Edit
            }
        ));
    }

    assert_eq!(repo.team_entity_access_calls.load(Ordering::SeqCst), 7);
}

#[tokio::test]
async fn team_scoped_bot_enforces_the_required_item_permission() {
    let repo = MockRepo::new().with_team_entity_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .generate_bot_entity_access_receipt::<EditAccessLevel>(
            test_bot_id(),
            test_bot_scope(),
            &Uuid::new_v4().to_string(),
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn team_scoped_bot_without_item_access_is_unauthorized() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());

    let result = service
        .generate_bot_entity_access_receipt::<ViewAccessLevel>(
            test_bot_id(),
            test_bot_scope(),
            &Uuid::new_v4().to_string(),
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn team_scoped_bot_channel_role_succeeds() {
    let bot_id = test_bot_id();
    let repo =
        MockRepo::new().with_team_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
    let service = EntityAccessServiceImpl::new(repo);

    let receipt = service
        .generate_bot_entity_access_receipt::<MemberParticipantRole>(
            bot_id,
            test_bot_scope(),
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await
        .unwrap();

    assert_eq!(receipt.get_authenticated_bot().unwrap().bot_id(), bot_id);
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::ChannelRole {
            role: ParticipantRole::Member
        }
    ));
}

#[tokio::test]
async fn team_scoped_bot_channel_errors_are_preserved() {
    for (result, expected_not_found) in [
        (ChannelRoleResult::NoAccess, false),
        (ChannelRoleResult::NotFound, true),
    ] {
        let repo = MockRepo::new().with_team_channel_role(result);
        let service = EntityAccessServiceImpl::new(repo);
        let error = service
            .generate_bot_entity_access_receipt::<MemberParticipantRole>(
                test_bot_id(),
                test_bot_scope(),
                "11111111-1111-1111-1111-111111111111",
                EntityType::Channel,
            )
            .await
            .expect_err("channel access must fail");

        if expected_not_found {
            assert!(matches!(error, AccessError::NotFound(_)));
        } else {
            assert!(matches!(error, AccessError::Unauthorized));
        }
    }
}

#[tokio::test]
async fn team_scoped_bot_malformed_channel_id_is_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo.clone());

    let result = service
        .generate_bot_entity_access_receipt::<MemberParticipantRole>(
            test_bot_id(),
            test_bot_scope(),
            "not-a-uuid",
            EntityType::Channel,
        )
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
    assert_eq!(repo.team_repository_calls(), 0);
}

#[tokio::test]
async fn team_scoped_bot_foreign_entity_access_is_view_only() {
    let repo = MockRepo::new().with_team_foreign_entity_access(true);
    let service = EntityAccessServiceImpl::new(repo);

    let receipt = service
        .generate_bot_entity_access_receipt::<ViewAccessLevel>(
            test_bot_id(),
            test_bot_scope(),
            FOREIGN_ENTITY_ID,
            EntityType::ForeignEntity,
        )
        .await
        .unwrap();
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View
        }
    ));

    let result = service
        .generate_bot_entity_access_receipt::<CommentAccessLevel>(
            test_bot_id(),
            test_bot_scope(),
            FOREIGN_ENTITY_ID,
            EntityType::ForeignEntity,
        )
        .await;
    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn team_scoped_bot_crm_access_is_always_view_only() {
    let repository_access = CrmEntityAccess {
        access_level: AccessLevel::Owner,
        team_id: test_team_id(),
        team_role: TeamRole::Owner,
    };
    let repo = MockRepo::new()
        .with_team_crm_company_access(repository_access)
        .with_team_crm_contact_access(repository_access);
    let service = EntityAccessServiceImpl::new(repo);

    for entity_type in [EntityType::CrmCompany, EntityType::CrmContact] {
        let entity_id = Uuid::new_v4().to_string();
        let receipt = service
            .generate_bot_entity_access_receipt::<ViewAccessLevel>(
                test_bot_id(),
                test_bot_scope(),
                &entity_id,
                entity_type,
            )
            .await
            .unwrap();
        assert!(matches!(
            receipt.entity_permission(),
            EntityPermission::AccessLevel {
                access_level: AccessLevel::View
            }
        ));

        let result = service
            .generate_bot_entity_access_receipt::<EditAccessLevel>(
                test_bot_id(),
                test_bot_scope(),
                &entity_id,
                entity_type,
            )
            .await;
        assert!(matches!(result, Err(AccessError::Unauthorized)));
    }
}

#[tokio::test]
async fn team_scoped_bot_hidden_or_other_team_crm_rows_are_unauthorized() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());

    for entity_type in [EntityType::CrmCompany, EntityType::CrmContact] {
        let result = service
            .generate_bot_entity_access_receipt::<ViewAccessLevel>(
                test_bot_id(),
                test_bot_scope(),
                &Uuid::new_v4().to_string(),
                entity_type,
            )
            .await;
        assert!(matches!(result, Err(AccessError::Unauthorized)));
    }
}

#[tokio::test]
async fn team_scoped_bot_receives_member_role_only_for_the_scoped_team() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());
    let receipt = service
        .generate_bot_entity_access_receipt::<MemberTeamRole>(
            test_bot_id(),
            test_bot_scope(),
            &test_team_id().to_string(),
            EntityType::Team,
        )
        .await
        .unwrap();
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::TeamRole {
            role: TeamRole::Member
        }
    ));

    let result = service
        .generate_bot_entity_access_receipt::<AdminTeamRole>(
            test_bot_id(),
            test_bot_scope(),
            &test_team_id().to_string(),
            EntityType::Team,
        )
        .await;
    assert!(matches!(result, Err(AccessError::Unauthorized)));

    let result = service
        .generate_bot_entity_access_receipt::<MemberTeamRole>(
            test_bot_id(),
            test_bot_scope(),
            &Uuid::new_v4().to_string(),
            EntityType::Team,
        )
        .await;
    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn bot_team_receipts_reject_malformed_team_ids() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());

    for scope in [test_bot_scope(), test_user_bot_scope(None)] {
        let result = service
            .generate_bot_entity_access_receipt::<MemberTeamRole>(
                test_bot_id(),
                scope,
                "not-a-uuid",
                EntityType::Team,
            )
            .await;
        assert!(matches!(result, Err(AccessError::BadRequest(_))));
    }
}

#[tokio::test]
async fn team_scoped_bot_unsupported_types_are_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo.clone());

    for entity_type in [
        EntityType::User,
        EntityType::ChannelMessage,
        EntityType::StaticFile,
    ] {
        let result = service
            .generate_bot_entity_access_receipt::<AnyEntityPermission>(
                test_bot_id(),
                test_bot_scope(),
                "unsupported-entity",
                entity_type,
            )
            .await;

        assert!(matches!(result, Err(AccessError::BadRequest(_))));
    }
    assert_eq!(repo.team_repository_calls(), 0);
}

#[tokio::test]
async fn test_generate_receipt_foreign_entity_view_requirement_succeeds() {
    let repo = MockRepo::new().with_foreign_entity_access(true);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<ViewAccessLevel>(
            &user_id,
            None,
            FOREIGN_ENTITY_ID,
            EntityType::ForeignEntity,
        )
        .await
        .unwrap();

    assert_eq!(receipt.entity().entity_id, FOREIGN_ENTITY_ID);
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_foreign_entity_view_access_fails_comment_requirement() {
    let repo = MockRepo::new().with_foreign_entity_access(true);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<CommentAccessLevel>(
            &user_id,
            None,
            FOREIGN_ENTITY_ID,
            EntityType::ForeignEntity,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

// --- minimum access level enforcement tests ---

#[tokio::test]
async fn test_generate_receipt_view_access_satisfies_view_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<ViewAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_edit_access_satisfies_view_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<ViewAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_owner_access_satisfies_owner_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<OwnerAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Owner
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_view_access_fails_comment_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<CommentAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_view_access_fails_edit_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::View);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<EditAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_edit_access_fails_owner_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Edit);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<OwnerAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_comment_access_fails_edit_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Comment);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<EditAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_comment_access_satisfies_comment_requirement() {
    let repo = MockRepo::new().with_document_access(AccessLevel::Comment);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<CommentAccessLevel>(
            &user_id,
            None,
            "doc-1",
            EntityType::Document,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Comment
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_channel_with_role() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<MemberParticipantRole>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await
        .unwrap();

    assert!(matches!(receipt.auth(), EntityAccessAuth::Authenticated(_)));
    assert_eq!(
        receipt.entity().entity_id,
        "11111111-1111-1111-1111-111111111111"
    );
    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::ChannelRole {
            role: ParticipantRole::Admin
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_channel_view_only_satisfies_view_only_requirement() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::ViewOnly);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<ViewOnly>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::ChannelViewOnly
    ));
}

#[tokio::test]
async fn test_generate_receipt_channel_view_only_fails_member_requirement() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::ViewOnly);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<MemberParticipantRole>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_channel_member_fails_edit_requirement() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Member));
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<AdminParticipantRole>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_channel_admin_satisfies_edit_requirement() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let receipt = service
        .generate_entity_access_receipt::<AdminParticipantRole>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await
        .unwrap();

    assert!(matches!(
        receipt.entity_permission(),
        EntityPermission::ChannelRole {
            role: ParticipantRole::Admin
        }
    ));
}

#[tokio::test]
async fn test_generate_receipt_channel_admin_fails_owner_requirement() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::Role(ParticipantRole::Admin));
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<OwnerParticipantRole>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn test_generate_receipt_channel_not_found_returns_not_found() {
    let repo = MockRepo::new().with_channel_role(ChannelRoleResult::NotFound);
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<MemberParticipantRole>(
            &user_id,
            None,
            "11111111-1111-1111-1111-111111111111",
            EntityType::Channel,
        )
        .await;

    assert!(matches!(result, Err(AccessError::NotFound(_))));
}

#[tokio::test]
async fn test_generate_receipt_unsupported_type_returns_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .generate_entity_access_receipt::<ViewAccessLevel>(
            &user_id,
            None,
            "team-1",
            EntityType::Team,
        )
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

// --- get_users_by_entity tests ---

#[tokio::test]
async fn test_get_users_by_entity_document_returns_users() {
    let users = vec![
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
    ];
    let repo = MockRepo::new().with_document_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000001", EntityType::Document)
        .await
        .unwrap();

    assert_eq!(result.len(), 2);
    assert_eq!(result[0].to_string(), "macro|[email protected]");
    assert_eq!(result[1].to_string(), "macro|[email protected]");
}

/// Sessions grant their owner and their originating channel, both of which
/// the generic accessor expansion reads, so they fan out like documents do.
#[tokio::test]
async fn test_get_users_by_entity_agent_session_returns_users() {
    let users = vec![
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
    ];
    let repo = MockRepo::new().with_agent_session_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity(
            "00000000-0000-0000-0000-00000000000a",
            EntityType::AgentSession,
        )
        .await
        .unwrap();

    assert_eq!(result, users);
}

#[tokio::test]
async fn test_get_users_by_entity_document_returns_empty_when_no_users() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000001", EntityType::Document)
        .await
        .unwrap();

    assert!(result.is_empty());
}

#[tokio::test]
async fn test_get_users_by_entity_chat_returns_users() {
    let users = vec![user_id("macro|[email protected]")];
    let repo = MockRepo::new().with_chat_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000002", EntityType::Chat)
        .await
        .unwrap();

    assert_eq!(result.len(), 1);
    assert_eq!(result[0].to_string(), "macro|[email protected]");
}

#[tokio::test]
async fn test_get_users_by_entity_chat_returns_empty_when_no_users() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000002", EntityType::Chat)
        .await
        .unwrap();

    assert!(result.is_empty());
}

#[tokio::test]
async fn test_get_users_by_entity_project_returns_users() {
    let users = vec![
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
    ];
    let repo = MockRepo::new().with_project_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000003", EntityType::Project)
        .await
        .unwrap();

    assert_eq!(result.len(), 3);
    assert_eq!(result[0].to_string(), "macro|[email protected]");
    assert_eq!(result[1].to_string(), "macro|[email protected]");
    assert_eq!(result[2].to_string(), "macro|[email protected]");
}

#[tokio::test]
async fn test_get_users_by_entity_project_returns_empty_when_no_users() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000003", EntityType::Project)
        .await
        .unwrap();

    assert!(result.is_empty());
}

#[tokio::test]
async fn test_get_users_by_entity_thread_returns_users() {
    let users = vec![
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
    ];
    let repo = MockRepo::new().with_thread_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity(
            "00000000-0000-0000-0000-000000000004",
            EntityType::EmailThread,
        )
        .await
        .unwrap();

    assert_eq!(result.len(), 2);
    assert_eq!(result[0].to_string(), "macro|[email protected]");
    assert_eq!(result[1].to_string(), "macro|[email protected]");
}

#[tokio::test]
async fn test_get_users_by_entity_thread_returns_empty_when_no_users() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity(
            "00000000-0000-0000-0000-000000000004",
            EntityType::EmailThread,
        )
        .await
        .unwrap();

    assert!(result.is_empty());
}

/// A row has no grants of its own: whoever can reach its database hears
/// about it, and a row that no longer exists has no one to tell.
#[tokio::test]
async fn test_get_users_by_entity_database_row_reaches_its_databases_users() {
    let users = vec![
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
    ];
    let service = EntityAccessServiceImpl::new(
        MockRepo::new()
            .with_database_row_database(Uuid::from_u128(0xdb000000_0000_0000_0000_000000000001))
            .with_database_users(users.clone()),
    );
    assert_eq!(
        service
            .get_users_by_entity(
                "70000000-0000-0000-0000-000000000001",
                EntityType::DatabaseRow
            )
            .await
            .unwrap(),
        users
    );

    let gone = EntityAccessServiceImpl::new(MockRepo::new().with_database_users(users));
    assert_eq!(
        gone.get_users_by_entity(
            "70000000-0000-0000-0000-000000000001",
            EntityType::DatabaseRow
        )
        .await
        .unwrap(),
        Vec::<MacroUserIdStr<'static>>::new()
    );
}

#[tokio::test]
async fn test_get_users_by_entity_database_returns_users() {
    let users = vec![
        user_id("macro|[email protected]"),
        user_id("macro|[email protected]"),
    ];
    let repo = MockRepo::new().with_database_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000004", EntityType::Database)
        .await
        .unwrap();

    assert_eq!(result.len(), 2);
    assert_eq!(result[0].to_string(), "macro|[email protected]");
    assert_eq!(result[1].to_string(), "macro|[email protected]");
}

#[tokio::test]
async fn test_get_users_by_entity_database_returns_empty_when_no_users() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000004", EntityType::Database)
        .await
        .unwrap();

    assert!(result.is_empty());
}

#[tokio::test]
async fn test_get_users_by_entity_database_rejects_invalid_uuid() {
    let repo = MockRepo::new().with_database_users(vec![user_id("macro|[email protected]")]);
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("not-a-uuid", EntityType::Database)
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

#[tokio::test]
async fn test_get_users_by_entity_channel_returns_users() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("11111111-1111-1111-1111-111111111111", EntityType::Channel)
        .await;

    assert!(result.is_ok());
    assert!(result.unwrap().is_empty());
}

#[tokio::test]
async fn test_get_users_by_entity_team_returns_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("team-1", EntityType::Team)
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

#[tokio::test]
async fn test_get_users_by_entity_user_returns_bad_request() {
    let repo = MockRepo::new();
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("user-1", EntityType::User)
        .await;

    assert!(matches!(result, Err(AccessError::BadRequest(_))));
}

#[tokio::test]
async fn test_get_users_by_entity_document_with_single_user() {
    let users = vec![user_id("macro|[email protected]")];
    let repo = MockRepo::new().with_document_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000001", EntityType::Document)
        .await
        .unwrap();

    assert_eq!(result.len(), 1);
    assert_eq!(result[0].to_string(), "macro|[email protected]");
}

#[tokio::test]
async fn test_get_users_by_entity_project_with_many_users() {
    let users: Vec<MacroUserIdStr<'static>> = (0..50)
        .map(|i| user_id(&format!("macro|user{}@test.com", i)))
        .collect();
    let repo = MockRepo::new().with_project_users(users.clone());
    let service = EntityAccessServiceImpl::new(repo);

    let result = service
        .get_users_by_entity("00000000-0000-0000-0000-000000000003", EntityType::Project)
        .await
        .unwrap();

    assert_eq!(result.len(), 50);
    for (i, u) in result.iter().enumerate() {
        assert_eq!(u.to_string(), format!("macro|user{}@test.com", i));
    }
}

#[tokio::test]
async fn document_session_access_tracks_current_document_permission() {
    let repo = MockRepo::new();
    *repo.agent_session_parent.lock().await = Some(AgentSessionParent::Document("doc".into()));
    let service = EntityAccessServiceImpl::new(repo.clone());
    for (permission, expected) in [
        (Some(AccessLevel::View), Some(AccessLevel::View)),
        (Some(AccessLevel::Comment), Some(AccessLevel::Edit)),
        (Some(AccessLevel::Owner), Some(AccessLevel::Edit)),
        (None, None),
    ] {
        *repo.document_access.lock().await = permission;
        assert_eq!(
            service
                .get_access_level(None, "session", EntityType::AgentSession)
                .await
                .unwrap(),
            expected
        );
    }
    *repo.agent_session_access.lock().await = Some(AccessLevel::Owner);
    assert_eq!(
        service
            .get_access_level(None, "session", EntityType::AgentSession)
            .await
            .unwrap(),
        Some(AccessLevel::Owner)
    );
}

#[tokio::test]
async fn standalone_call_recipients_use_explicit_entity_grants() {
    let repo = MockRepo::new();
    let granted = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    *repo.call_channel.lock().await = Some(CallChannelInfo {
        channel_id: None,
        share_permission_id: "share".into(),
    });
    *repo.call_users.lock().await = vec![granted.clone()];
    *repo.channel_users.lock().await = vec![
        MacroUserIdStr::parse_from_str("macro|[email protected]")
            .unwrap()
            .into_owned(),
    ];
    let service = EntityAccessServiceImpl::new(repo);
    let users = service
        .get_users_by_entity(&Uuid::now_v7().to_string(), EntityType::Call)
        .await
        .unwrap();
    assert_eq!(users, vec![granted]);
}

#[tokio::test]
async fn channel_call_recipients_still_use_channel_membership() {
    let repo = MockRepo::new();
    let member = MacroUserIdStr::parse_from_str("macro|[email protected]")
        .unwrap()
        .into_owned();
    *repo.call_channel.lock().await = Some(CallChannelInfo {
        channel_id: Some(Uuid::now_v7()),
        share_permission_id: "share".into(),
    });
    *repo.channel_users.lock().await = vec![member.clone()];
    let service = EntityAccessServiceImpl::new(repo);
    let users = service
        .get_users_by_entity(&Uuid::now_v7().to_string(), EntityType::Call)
        .await
        .unwrap();
    assert_eq!(users, vec![member]);
}

#[tokio::test]
async fn database_row_receipts_share_the_access_lookup() {
    let repo = MockRepo::new().with_database_row_access(AccessLevel::Edit);
    let calls = repo.database_row_access_calls.clone();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();
    let row_ids = vec![
        "0198a805-3e22-75b2-97eb-d9c6b91accb1".to_string(),
        "0198a805-3e22-75b2-97eb-d9c6b91accb2".to_string(),
        "invalid".to_string(),
    ];
    let receipts = service
        .generate_database_row_view_access_receipts(&user_id, &row_ids)
        .await;
    assert_eq!(receipts.len(), 3);
    for row_id in &row_ids[..2] {
        let receipt = receipts[row_id].as_ref().unwrap();
        assert_eq!(receipt.entity().entity_id, *row_id);
        assert_eq!(receipt.entity().entity_type, EntityType::DatabaseRow);
        assert!(matches!(
            receipt.entity_permission(),
            EntityPermission::AccessLevel {
                access_level: AccessLevel::Edit
            }
        ));
    }
    assert!(matches!(
        receipts["invalid"],
        Err(AccessError::BadRequest(_))
    ));
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn database_row_receipts_deny_rows_without_a_grant() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());
    let user_id = test_user_id();
    let receipts = service
        .generate_database_row_view_access_receipts(
            &user_id,
            &["0198a805-3e22-75b2-97eb-d9c6b91accb1".to_string()],
        )
        .await;
    assert!(matches!(
        receipts["0198a805-3e22-75b2-97eb-d9c6b91accb1"],
        Err(AccessError::Unauthorized)
    ));
}

const FORM_ID: &str = "0199b1f2-3e22-75b2-97eb-d9c6b91accb0";

#[tokio::test]
async fn a_form_permission_is_the_repository_form_access() {
    let repo = MockRepo::new().with_form_access(AccessLevel::Edit);
    let callers = repo.form_access_callers.clone();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(Some(&user_id), FORM_ID, EntityType::Form, None)
        .await
        .unwrap();

    assert_eq!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    );
    assert_eq!(
        *callers.lock().await,
        vec![Some(user_id.as_ref().to_string())]
    );
}

#[tokio::test]
async fn a_form_without_access_is_unauthorized() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(Some(&user_id), FORM_ID, EntityType::Form, None)
        .await;

    assert!(matches!(result, Err(AccessError::Unauthorized)));
}

#[tokio::test]
async fn public_form_access_asks_the_repository_without_a_user() {
    let repo = MockRepo::new().with_form_access(AccessLevel::View);
    let callers = repo.form_access_callers.clone();
    let service = EntityAccessServiceImpl::new(repo);

    assert_eq!(
        service
            .check_public_access(FORM_ID, EntityType::Form, AccessLevel::View)
            .await
            .unwrap(),
        AccessLevel::View
    );
    assert!(matches!(
        service
            .check_public_access(FORM_ID, EntityType::Form, AccessLevel::Edit)
            .await,
        Err(AccessError::Unauthorized)
    ));
    assert_eq!(*callers.lock().await, vec![None, None]);
}

#[tokio::test]
async fn a_members_form_has_no_public_access() {
    let service = EntityAccessServiceImpl::new(MockRepo::new());

    assert!(matches!(
        service
            .check_public_access(FORM_ID, EntityType::Form, AccessLevel::View)
            .await,
        Err(AccessError::Unauthorized)
    ));
}

#[tokio::test]
async fn a_form_audience_is_its_entity_access_users() {
    let respondent = MacroUserIdStr::try_from_email("[email protected]")
        .unwrap()
        .into_owned();
    let service =
        EntityAccessServiceImpl::new(MockRepo::new().with_form_users(vec![respondent.clone()]));

    assert_eq!(
        service
            .get_users_by_entity(FORM_ID, EntityType::Form)
            .await
            .unwrap(),
        vec![respondent]
    );
}

#[tokio::test]
async fn a_team_bot_reaches_a_form_through_the_team_access_pool() {
    let repo = MockRepo::new().with_team_entity_access(AccessLevel::Edit);
    let requests = repo.team_entity_requests.clone();
    let service = EntityAccessServiceImpl::new(repo);

    let receipt = service
        .generate_bot_entity_access_receipt::<EditAccessLevel>(
            BotId::new_from_uuid(Uuid::from_u128(1)),
            BotAccessScope::Team {
                team_id: Uuid::from_u128(2),
            },
            FORM_ID,
            EntityType::Form,
        )
        .await
        .unwrap();

    assert_eq!(
        receipt.entity_permission(),
        &EntityPermission::AccessLevel {
            access_level: AccessLevel::Edit
        }
    );
    assert_eq!(
        *requests.lock().await,
        vec![(FORM_ID.to_string(), EntityType::Form)]
    );
}

#[tokio::test]
async fn accessible_forms_are_the_repository_listing() {
    let shared = Uuid::parse_str("0199b1f2-3e22-75b2-97eb-d9c6b91accb1").unwrap();
    let owned = Uuid::parse_str("0199b1f2-3e22-75b2-97eb-d9c6b91accb2").unwrap();
    let repo = MockRepo::new().with_form_access_list(vec![
        (shared, AccessLevel::View),
        (owned, AccessLevel::Owner),
    ]);
    let service = EntityAccessServiceImpl::new(repo);

    assert_eq!(
        service.accessible_forms(&test_user_id()).await.unwrap(),
        vec![(shared, AccessLevel::View), (owned, AccessLevel::Owner)]
    );
}

#[tokio::test]
async fn pipeline_receipts_use_their_own_grants() {
    let repo = MockRepo::new().with_database_access(AccessLevel::Owner);
    let service = EntityAccessServiceImpl::new(repo.clone());
    let user = MacroUserIdStr::try_from_email("[email protected]").unwrap();
    let id = Uuid::now_v7().to_string();
    assert!(
        service
            .generate_entity_access_receipt::<ViewAccessLevel>(
                &user,
                None,
                &id,
                EntityType::CrmPipeline
            )
            .await
            .is_err()
    );
    *repo.pipeline_access.lock().await = Some(AccessLevel::Edit);
    assert!(
        service
            .generate_entity_access_receipt::<EditAccessLevel>(
                &user,
                None,
                &id,
                EntityType::CrmPipeline
            )
            .await
            .is_ok()
    );
    assert!(
        service
            .generate_entity_access_receipt::<OwnerAccessLevel>(
                &user,
                None,
                &id,
                EntityType::CrmPipeline
            )
            .await
            .is_err()
    );
}

const EXTERNAL_CHAT_ID: &str = "0199b1f2-3e22-75b2-97eb-d9c6b91accb1";

#[tokio::test]
async fn a_external_chat_permission_is_the_repository_group_access() {
    let repo = MockRepo::new()
        .with_external_chat_access(AccessLevel::View)
        .with_form_access(AccessLevel::Edit);
    let callers = repo.external_chat_access_callers.clone();
    let service = EntityAccessServiceImpl::new(repo);
    let user_id = test_user_id();

    let result = service
        .get_entity_permission(
            Some(&user_id),
            EXTERNAL_CHAT_ID,
            EntityType::ExternalChat,
            None,
        )
        .await
        .unwrap();

    assert_eq!(
        result,
        EntityPermission::AccessLevel {
            access_level: AccessLevel::View
        }
    );
    assert_eq!(
        *callers.lock().await,
        vec![Some(user_id.as_ref().to_string())]
    );
}