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.

55.1 KB
Raw Blame
//! Implementation for TeamRepository using MacroDB.
use crate::domain::{
    model::{
        AcceptedTeamInvite, CreateTeamError, DueInviteReminder, InviteUsersToTeamError,
        PatchTeamRequest, RemoveTeamInviteError, RemoveUserFromTeamError, SeatPlan, Team,
        TeamError, TeamInvite, TeamInviteDetails, TeamInviteLinkTeam, TeamInviteLinkToken,
        TeamInviteSnapshot, TeamMember, TeamMembers, TeamPlan, TeamRole, TeamWithMembers,
        ToggleAutoJoinDomainError, is_generic_email_domain, normalize_team_slug,
    },
    owned_entity_cleanup::ClearedTeam,
    team_repo::{TeamMembersService, TeamRepository},
    team_service::invite_resend_interval,
};
use entity_access_db_utils::{EntityAccessSourceType, delete_source_grants, team_share};
use macro_user_id::{
    cowlike::CowLike,
    email::{Email, ReadEmailParts},
    lowercased::Lowercase,
    user_id::MacroUserIdStr,
};
use model_owner::Owner;
use model_user::Language;
use models_permissions::share_permission::LinkShare;
use sqlx::{PgPool, Row};
use std::str::FromStr;

/// utility fn for queries to create a sqlx err
fn type_err<E: std::fmt::Display>(e: E) -> sqlx::Error {
    sqlx::Error::TypeNotFound {
        type_name: e.to_string(),
    }
}

mod invite_link;
#[cfg(test)]
mod test;

/// The TeamRepositoryImpl struct is a wrapper around sqlx::PgPool connected to macrodb.
#[derive(Clone)]
pub struct TeamRepositoryImpl {
    /// The underlying sqlx::PgPool connected to macrodb.
    pool: PgPool,
}

impl TeamRepositoryImpl {
    /// Creates a new instance of TeamRepositoryImpl
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }
}

impl TeamRepositoryImpl {
    /// Bumps the teams seat count by the quantity number (positive or negative)
    #[tracing::instrument(skip(transaction), err)]
    async fn bump_seat_count<'t>(
        transaction: &mut sqlx::Transaction<'t, sqlx::Postgres>,
        team_id: &uuid::Uuid,
        quantity: i32,
    ) -> Result<(), anyhow::Error> {
        sqlx::query!(
            r#"
            UPDATE team
            SET seat_count = seat_count + $2
            WHERE id = $1
        "#,
            team_id,
            quantity
        )
        .execute(transaction.as_mut())
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn create_team_inner(
        &self,
        user_id: &MacroUserIdStr<'_>,
        team_name: &str,
        team_slug: &str,
        subscription_id: Option<&stripe::SubscriptionId>,
        owner_plan: SeatPlan,
        auto_join_domain: Option<&str>,
    ) -> Result<Team, sqlx::Error> {
        let mut transaction = self.pool.begin().await?;

        let id = macro_uuid::generate_uuid_v7();

        let team = sqlx::query!(
            r#"
            INSERT INTO team (
                id, name, slug, owner_id, seat_count, subscription_id, paying, auto_join_domain
            )
            VALUES ($1, $2, $3, $4, 1, $5, $6, $7)
            RETURNING id, name, slug, owner_id, enterprise, allow_non_admin_invites,
                auto_join_domain,
                default_link_share as "default_link_share: LinkShare",
                language as "language: Language"
            "#,
            id,
            team_name,
            team_slug,
            user_id.as_ref(),
            subscription_id.map(|s| s.to_string()),
            subscription_id.is_some(),
            auto_join_domain,
        )
        .try_map(|row| {
            Ok(Team {
                id: row.id,
                name: row.name,
                slug: row.slug,
                owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)
                    .map_err(type_err)?
                    .into_owned(),
                // New teams have no team_crm_settings row yet.
                crm_enabled: false,
                auto_join_domain: row.auto_join_domain,
                enterprise: row.enterprise,
                allow_non_admin_invites: row.allow_non_admin_invites,
                default_link_share: row.default_link_share,
                language: row.language,
            })
        })
        .fetch_one(&mut *transaction)
        .await?;

        sqlx::query!(
            r#"
            INSERT INTO team_user (team_id, user_id, team_role, plan)
            VALUES ($1, $2, 'owner', $3)
            "#,
            &team.id,
            user_id.as_ref(),
            owner_plan as _,
        )
        .execute(&mut *transaction)
        .await?;

        // Seed the team's CRM settings row. `crm_enabled` defaults to
        // FALSE — toggled on later via `PATCH /team/crm`. Created in
        // the same tx as the team itself so the row always exists for
        // any team that exists.
        sqlx::query!(
            r#"
            INSERT INTO team_crm_settings (team_id)
            VALUES ($1)
            "#,
            &team.id,
        )
        .execute(&mut *transaction)
        .await?;

        transaction.commit().await?;

        Ok(team)
    }
}

impl From<sqlx::Error> for TeamError {
    fn from(e: sqlx::Error) -> Self {
        match e {
            sqlx::Error::RowNotFound => Self::TeamDoesNotExist,
            _ => Self::StorageLayerError(e.into()),
        }
    }
}

impl From<sqlx::Error> for CreateTeamError {
    fn from(e: sqlx::Error) -> Self {
        Self::StorageLayerError(e.into())
    }
}

impl From<sqlx::Error> for InviteUsersToTeamError {
    fn from(e: sqlx::Error) -> Self {
        Self::StorageLayerError(e.into())
    }
}

impl From<sqlx::Error> for RemoveUserFromTeamError {
    fn from(e: sqlx::Error) -> Self {
        Self::StorageLayerError(e.into())
    }
}

impl From<sqlx::Error> for RemoveTeamInviteError {
    fn from(e: sqlx::Error) -> Self {
        Self::StorageLayerError(e.into())
    }
}

impl From<sqlx::Error> for ToggleAutoJoinDomainError {
    fn from(e: sqlx::Error) -> Self {
        Self::TeamError(e.into())
    }
}

impl TeamMembersService for TeamRepositoryImpl {
    #[tracing::instrument(skip(self), err)]
    async fn list_team_members(
        &self,
        entity_access_receipt: entity_access::domain::models::EntityAccessReceipt<
            entity_access::domain::models::MemberTeamRole,
        >,
    ) -> Result<TeamMembers, TeamError> {
        let team_id =
            macro_uuid::string_to_uuid(&entity_access_receipt.entity().entity_id).unwrap();

        let members = self.get_team_by_id(&team_id).await?.members;
        let invited = self.get_team_invites(&team_id).await?;

        Ok(TeamMembers { members, invited })
    }
}

impl TeamRepository for TeamRepositoryImpl {
    #[tracing::instrument(skip(self), err)]
    async fn get_stripe_customer_id(
        &self,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<Option<stripe::CustomerId>, TeamError> {
        let stripe_customer_id = sqlx::query!(
            r#"
            SELECT "stripeCustomerId" as "stripe_customer_id?"
            FROM "User"
            WHERE id = $1
        "#,
            user_id.as_ref()
        )
        .map(|row| row.stripe_customer_id)
        .fetch_one(&self.pool)
        .await?;

        if let Some(stripe_customer_id) = stripe_customer_id {
            let stripe_customer_id =
                stripe::CustomerId::from_str(&stripe_customer_id).map_err(|_| {
                    TeamError::StorageLayerError(anyhow::anyhow!(
                        "unable to parse stripe customer id"
                    ))
                })?;
            Ok(Some(stripe_customer_id))
        } else {
            Ok(None)
        }
    }

    #[tracing::instrument(skip(self), err)]
    #[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
    async fn has_user_trialed(&self, user_id: &MacroUserIdStr<'_>) -> Result<bool, TeamError> {
        let has_trialed = sqlx::query_scalar::<_, bool>(
            r#"
            SELECT mu.has_trialed
            FROM "User" u
            INNER JOIN macro_user mu ON mu.id = u.macro_user_id
            WHERE u.id = $1
            "#,
        )
        .bind(user_id.as_ref())
        .fetch_one(&self.pool)
        .await?;

        Ok(has_trialed)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_subscription_id(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<Option<stripe::SubscriptionId>, TeamError> {
        let team_subscription_id = sqlx::query!(
            r#"
            SELECT subscription_id
            FROM team
            WHERE id = $1
        "#,
            team_id,
        )
        .map(|row| row.subscription_id)
        .fetch_one(&self.pool)
        .await?;

        let team_subscription_id = if let Some(subscription_id) = team_subscription_id {
            Some(
                stripe::SubscriptionId::from_str(&subscription_id)
                    .map_err(|_| TeamError::InvalidSubscriptionId)?,
            )
        } else {
            None
        };

        Ok(team_subscription_id)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_payment_status(&self, team_id: &uuid::Uuid) -> Result<bool, TeamError> {
        let paying = sqlx::query_scalar!(
            r#"
            SELECT paying
            FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .fetch_one(&self.pool)
        .await?;

        Ok(paying)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_enterprise_status(&self, team_id: &uuid::Uuid) -> Result<bool, TeamError> {
        let enterprise = sqlx::query_scalar!(
            r#"
            SELECT enterprise
            FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .fetch_one(&self.pool)
        .await?;

        Ok(enterprise)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_owner(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<MacroUserIdStr<'static>, TeamError> {
        let owner_id = sqlx::query!(
            r#"
            SELECT owner_id
            FROM team
            WHERE id = $1
        "#,
            team_id,
        )
        .map(|row| row.owner_id)
        .fetch_one(&self.pool)
        .await?;

        MacroUserIdStr::parse_from_str(owner_id.as_str())
            .map(|id| id.into_owned())
            .map_err(|error| TeamError::StorageLayerError(error.into()))
    }

    #[tracing::instrument(skip(self), err)]
    async fn create_team(
        &self,
        user_id: &MacroUserIdStr<'_>,
        team_name: &str,
        team_slug: &str,
        subscription_id: Option<&stripe::SubscriptionId>,
        owner_plan: SeatPlan,
        auto_join_domain: Option<&str>,
    ) -> Result<Team, CreateTeamError> {
        if team_name.is_empty() || team_name.len() > 50 {
            return Err(CreateTeamError::InvalidTeamName(team_name.to_string()));
        }

        self.create_team_inner(
            user_id,
            team_name,
            team_slug,
            subscription_id,
            owner_plan,
            auto_join_domain,
        )
        .await
        .map_err(|e| e.into())
    }

    #[tracing::instrument(skip(self), err)]
    async fn move_github_app_installation_to_team_if_exists(
        &self,
        user_id: &MacroUserIdStr<'_>,
        team_id: &uuid::Uuid,
    ) -> Result<(), CreateTeamError> {
        sqlx::query!(
            r#"
            UPDATE github_app_installation
            SET source_id = $2::text,
                source_type = 'team'::github_app_installation_source_type
            WHERE source_id = $1
              AND source_type = 'user'::github_app_installation_source_type
            "#,
            user_id.as_ref(),
            team_id.to_string(),
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn invite_users_to_team(
        &self,
        team_id: &uuid::Uuid,
        invited_by: &MacroUserIdStr<'_>,
        invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
        is_agent: bool,
    ) -> Result<Vec<TeamInvite<'_>>, InviteUsersToTeamError> {
        let email_strings: Vec<String> = invites
            .iter()
            .map(|email| email.as_ref().to_string())
            .collect();

        let macro_user_ids: Vec<String> = invites
            .iter()
            .map(|email| format!("macro|{}", email.as_ref()))
            .collect();

        let team_invite_ids: Vec<uuid::Uuid> = invites
            .iter()
            .map(|_| macro_uuid::generate_uuid_v7())
            .collect();

        let mut transaction = self.pool.begin().await?;

        // Single query that filters out both already invited AND already on team
        let created_invites: Vec<(uuid::Uuid, uuid::Uuid, String, bool)> = sqlx::query!(
        r#"
            INSERT INTO team_invite (id, team_id, email, team_role, invited_by, created_at, last_sent_at, is_agent)
            SELECT
                t.id,
                $1::uuid,
                t.email,
                $2,
                $3::text,
                NOW(),
                NOW(),
                $7
            FROM UNNEST($4::uuid[], $5::text[], $6::text[]) AS t(id, email, user_id)
            WHERE NOT EXISTS (
                SELECT 1 FROM team_invite ti
                WHERE ti.team_id = $1 AND ti.email = t.email
            )
            AND NOT EXISTS (
                SELECT 1 FROM team_user tu
                WHERE tu.team_id = $1 AND tu.user_id = t.user_id
            )
            RETURNING id, team_id, email, is_agent
        "#,
        team_id,
        TeamRole::Member as _,
        invited_by.as_ref(),
        &team_invite_ids[..],
        &email_strings[..],
        &macro_user_ids[..],
        is_agent,
    )
    .map(|r| (r.id, r.team_id, r.email, r.is_agent))
    .fetch_all(&mut *transaction)
    .await?;

        // Also re-send existing invites whose email rate limit has passed;
        // sooner, the email would be dropped while `last_sent_at` moved on.
        let resent_invites: Vec<(uuid::Uuid, uuid::Uuid, String, bool)> = sqlx::query!(
            r#"
            SELECT id, team_id, email, is_agent
            FROM team_invite
            WHERE team_id = $1
              AND email = ANY($2::text[])
              AND last_sent_at <= NOW() - make_interval(secs => $3)
            "#,
            team_id,
            &email_strings[..],
            invite_resend_interval().as_secs_f64(),
        )
        .map(|r| (r.id, r.team_id, r.email, r.is_agent))
        .fetch_all(&mut *transaction)
        .await?;

        let to_email = |id: uuid::Uuid, team_id: uuid::Uuid, email: String, is_agent: bool| {
            Email::parse_from_str(&email)
                .ok()
                .map(|e| e.into_owned().lowercase())
                .map(|email| TeamInvite {
                    team_id,
                    team_invite_id: id,
                    email,
                    is_agent,
                })
        };

        // Combine new invites and resent invites
        let all_invites: Vec<TeamInvite<'static>> = created_invites
            .into_iter()
            .chain(resent_invites)
            .filter_map(|(id, team_id, email, is_agent)| to_email(id, team_id, email, is_agent))
            .collect();

        transaction.commit().await?;

        Ok(all_invites)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_new_invites(
        &self,
        team_id: &uuid::Uuid,
        invites: non_empty::NonEmpty<&[Email<Lowercase<'_>>]>,
    ) -> Result<Vec<Email<Lowercase<'static>>>, InviteUsersToTeamError> {
        let email_strings: Vec<String> = invites
            .iter()
            .map(|email| email.as_ref().to_string())
            .collect();

        let macro_user_ids: Vec<String> = invites
            .iter()
            .map(|email| format!("macro|{}", email.as_ref()))
            .collect();

        let rows = sqlx::query!(
            r#"
            SELECT t.email as "email!"
            FROM UNNEST($2::text[], $3::text[]) WITH ORDINALITY AS t(email, user_id, ord)
            WHERE NOT EXISTS (
                SELECT 1 FROM team_invite ti
                WHERE ti.team_id = $1 AND ti.email = t.email
            )
            AND NOT EXISTS (
                SELECT 1 FROM team_user tu
                WHERE tu.team_id = $1 AND tu.user_id = t.user_id
            )
            GROUP BY t.email
            ORDER BY MIN(t.ord)
            "#,
            team_id,
            &email_strings[..],
            &macro_user_ids[..],
        )
        .fetch_all(&self.pool)
        .await?;

        let mut new_invites = Vec::with_capacity(rows.len());
        for row in rows {
            let email = Email::parse_from_str(&row.email)
                .map(|email| email.into_owned().lowercase())
                .map_err(|e| {
                    InviteUsersToTeamError::StorageLayerError(anyhow::anyhow!(
                        "unable to parse email {e}"
                    ))
                })?;
            new_invites.push(email);
        }

        Ok(new_invites)
    }

    #[tracing::instrument(skip(self), err)]
    async fn mark_invites_sent(&self, invite_ids: &[uuid::Uuid]) -> Result<(), TeamError> {
        sqlx::query!(
            r#"
            UPDATE team_invite
            SET last_sent_at = NOW()
            WHERE id = ANY($1::uuid[])
            "#,
            invite_ids,
        )
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), fields(claimed = tracing::field::Empty), err)]
    async fn claim_due_invite_reminders(
        &self,
        limit: i64,
    ) -> Result<Vec<DueInviteReminder>, TeamError> {
        // The first reminder goes 3 days after the last email, the second 4
        // days after the first. Invites older than 14 days are left alone, so
        // a deploy never reminds people about invites from long ago. Skips
        // invites the invitee could not accept (the team stopped paying for
        // its subscription), already-members, and invites whose sender left
        // the team, since the email is written in the sender's name.
        let reminders = sqlx::query!(
            r#"
            WITH due AS (
                SELECT ti.id
                FROM team_invite ti
                JOIN team t ON t.id = ti.team_id
                WHERE ti.created_at > NOW() - INTERVAL '14 days'
                  AND (
                      (ti.reminders_sent = 0 AND ti.last_sent_at <= NOW() - INTERVAL '3 days')
                      OR (ti.reminders_sent = 1 AND ti.last_sent_at <= NOW() - INTERVAL '4 days')
                  )
                  AND (t.enterprise OR t.paying OR t.subscription_id IS NULL)
                  AND EXISTS (
                      SELECT 1 FROM team_user tu
                      WHERE tu.team_id = ti.team_id AND tu.user_id = ti.invited_by
                  )
                  AND NOT EXISTS (
                      SELECT 1 FROM team_user tu
                      WHERE tu.team_id = ti.team_id AND tu.user_id = 'macro|' || ti.email
                  )
                ORDER BY ti.created_at
                LIMIT $1
                FOR UPDATE OF ti SKIP LOCKED
            )
            UPDATE team_invite ti
            SET reminders_sent = ti.reminders_sent + 1,
                last_sent_at = NOW()
            FROM due, team t
            WHERE ti.id = due.id AND t.id = ti.team_id
            RETURNING
                ti.id,
                ti.team_id,
                t.name AS team_name,
                ti.email,
                ti.invited_by,
                ti.reminders_sent,
                t.enterprise,
                t.paying,
                t.subscription_id IS NOT NULL AS "has_subscription!",
                ti.is_agent
            "#,
            limit,
        )
        .fetch_all(&self.pool)
        .await?
        .into_iter()
        .map(|r| {
            Ok(DueInviteReminder {
                team_invite_id: r.id,
                team_id: r.team_id,
                team_name: r.team_name,
                email: r.email,
                invited_by: r.invited_by,
                reminder_number: u8::try_from(r.reminders_sent).map_err(anyhow::Error::from)?,
                enterprise: r.enterprise,
                paying: r.paying,
                has_subscription: r.has_subscription,
                is_agent: r.is_agent,
            })
        })
        .collect::<Result<Vec<_>, TeamError>>()?;
        tracing::Span::current().record("claimed", reminders.len());
        Ok(reminders)
    }

    #[tracing::instrument(skip(self), err)]
    #[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
    async fn remove_user_from_team(
        &self,
        team_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<TeamMember<'static>, RemoveUserFromTeamError> {
        let owner_id = self.get_team_owner(team_id).await?;

        if user_id.as_ref().eq(owner_id.as_ref()) {
            return Err(RemoveUserFromTeamError::CannotRemoveOwner);
        }

        let mut transaction = self.pool.begin().await?;

        let row = sqlx::query(
            r#"
            DELETE FROM team_user
            WHERE team_id = $1 AND user_id = $2
            RETURNING team_role, plan
            "#,
        )
        .bind(team_id)
        .bind(user_id.as_ref())
        .fetch_optional(&mut *transaction)
        .await?;

        let Some(row) = row else {
            return Err(RemoveUserFromTeamError::UserNotInTeam);
        };

        let removed_member = TeamMember {
            team_id: *team_id,
            user_id: user_id.clone().into_owned(),
            role: row.try_get("team_role")?,
            plan: row.try_get("plan")?,
        };

        TeamRepositoryImpl::bump_seat_count(&mut transaction, team_id, -1).await?;

        transaction.commit().await?;

        Ok(removed_member)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_invite_by_id(
        &self,
        team_invite_id: &uuid::Uuid,
    ) -> Result<TeamInvite<'_>, TeamError> {
        let team_invite: (uuid::Uuid, uuid::Uuid, String, bool) = sqlx::query!(
            r#"
            SELECT id, email, team_id, is_agent
            FROM team_invite
            WHERE id = $1
            "#,
            team_invite_id,
        )
        .map(|row| (row.id, row.team_id, row.email, row.is_agent))
        .fetch_one(&self.pool)
        .await
        .map_err(|e| match e {
            sqlx::Error::RowNotFound => TeamError::TeamInviteDoesNotExist,
            _ => e.into(),
        })?;

        let (id, team_id, email, is_agent) = team_invite;

        let team_invite: TeamInvite = TeamInvite {
            team_id,
            team_invite_id: id,
            email: Email::parse_from_str(&email)
                .map(|e| e.into_owned().lowercase())
                .map_err(|e| anyhow::anyhow!("unable to parse email {}", e))?,
            is_agent,
        };

        Ok(team_invite.to_owned())
    }

    #[tracing::instrument(skip(self), err)]
    async fn delete_team_invite(
        &self,
        team_id: &uuid::Uuid,
        team_invite_id: &uuid::Uuid,
    ) -> Result<(), RemoveTeamInviteError> {
        let mut transaction = self.pool.begin().await?;
        let result = sqlx::query!(
            r#"
            DELETE FROM team_invite
            WHERE id = $1 AND team_id = $2
            "#,
            team_invite_id,
            team_id,
        )
        .execute(&mut *transaction)
        .await?;

        if result.rows_affected() == 0 {
            return Err(RemoveTeamInviteError::TeamInviteDoesNotExist);
        }

        transaction.commit().await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn update_team_subscription(
        &self,
        team_id: &uuid::Uuid,
        subscription_id: &stripe::SubscriptionId,
    ) -> Result<(), TeamError> {
        sqlx::query!(
            r#"
            UPDATE team
            SET subscription_id = $2
            WHERE id = $1
            "#,
            team_id,
            subscription_id.to_string(),
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn update_team_payment_status(
        &self,
        team_id: &uuid::Uuid,
        paying: bool,
    ) -> Result<(), TeamError> {
        let result = sqlx::query!(
            r#"
            UPDATE team
            SET paying = $2
            WHERE id = $1
            "#,
            team_id,
            paying,
        )
        .execute(&self.pool)
        .await?;

        if result.rows_affected() == 0 {
            return Err(TeamError::TeamDoesNotExist);
        }

        Ok(())
    }

    #[tracing::instrument(skip(self, cleared), fields(team_id = %cleared.team_id()), err)]
    async fn delete_team(&self, cleared: &ClearedTeam) -> Result<(), TeamError> {
        let team_id = cleared.team_id();
        let mut transaction = self.pool.begin().await?;
        team_share::acquire_guard(&mut transaction).await?;

        delete_source_grants(
            &mut *transaction,
            EntityAccessSourceType::Team,
            &Owner::Team(team_id).principal_id(),
        )
        .await?;
        for bot_id in cleared.bot_ids() {
            delete_source_grants(
                &mut *transaction,
                EntityAccessSourceType::Bot,
                &Owner::Bot(*bot_id).principal_id(),
            )
            .await?;
        }

        sqlx::query!(
            r#"
            DELETE FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .execute(&mut *transaction)
        .await?;

        sqlx::query!(
            r#"
            DELETE FROM github_app_installation
            WHERE source_id = $1
              AND source_type = 'team'::github_app_installation_source_type
            "#,
            team_id.to_string(),
        )
        .execute(&mut *transaction)
        .await?;

        transaction.commit().await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_all_team_members(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<Vec<TeamMember<'_>>, TeamError> {
        let members = sqlx::query!(
            r#"
            SELECT user_id, 
                team_role as "team_role!: TeamRole",
                plan as "plan!: SeatPlan"
            FROM team_user
            WHERE team_id = $1
            "#,
            team_id,
        )
        .fetch_all(&self.pool)
        .await?;

        let members: Vec<Result<TeamMember, anyhow::Error>> = members
            .into_iter()
            .map(|row| {
                let user_id =
                    MacroUserIdStr::parse_from_str(&row.user_id).map(|id| id.into_owned());

                if let Ok(user_id) = user_id {
                    Ok(TeamMember {
                        user_id,
                        role: row.team_role,
                        plan: row.plan,
                        team_id: *team_id,
                    })
                } else {
                    Err(anyhow::anyhow!("unable to parse user id"))
                }
            })
            .collect();

        let members = members
            .into_iter()
            .filter_map(|member| member.ok())
            .collect();

        Ok(members)
    }

    #[tracing::instrument(skip(self), err)]
    #[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
    async fn accept_team_invite(
        &self,
        team_invite_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<AcceptedTeamInvite<'static>, TeamError> {
        let mut transaction = self.pool.begin().await?;

        let user_email = user_id.email_part().lowercase();

        // Get invite data before deleting it so the accept can be rolled back later.
        let invite = sqlx::query(
            r#"
            SELECT id, email, team_role, team_id, invited_by, created_at, last_sent_at, is_agent
            FROM team_invite
            WHERE id = $1 AND email = $2
            "#,
        )
        .bind(team_invite_id)
        .bind(user_email.as_ref())
        .fetch_one(&mut *transaction)
        .await?;

        let invite_snapshot = TeamInviteSnapshot {
            id: invite.try_get("id")?,
            team_id: invite.try_get("team_id")?,
            email: Email::parse_from_str(invite.try_get::<String, _>("email")?.as_str())
                .map(|e| e.into_owned().lowercase())
                .map_err(|e| TeamError::StorageLayerError(e.into()))?,
            team_role: invite.try_get("team_role")?,
            invited_by: MacroUserIdStr::parse_from_str(
                invite.try_get::<String, _>("invited_by")?.as_str(),
            )
            .map(|id| id.into_owned())
            .map_err(|e| TeamError::StorageLayerError(e.into()))?,
            created_at: chrono::DateTime::from_naive_utc_and_offset(
                invite.try_get("created_at")?,
                chrono::Utc,
            ),
            last_sent_at: chrono::DateTime::from_naive_utc_and_offset(
                invite.try_get("last_sent_at")?,
                chrono::Utc,
            ),
            is_agent: invite.try_get("is_agent")?,
        };

        // Assign user to team_user
        let team_member = sqlx::query(
            r#"
            INSERT INTO team_user (team_id, user_id, team_role)
            VALUES ($1, $2, $3)
            RETURNING user_id, team_role, team_id, plan
            "#,
        )
        .bind(invite_snapshot.team_id)
        .bind(user_id.as_ref())
        .bind(invite_snapshot.team_role)
        .fetch_one(&mut *transaction)
        .await?;

        // bump seat count
        let team_id: uuid::Uuid = team_member.try_get("team_id")?;
        TeamRepositoryImpl::bump_seat_count(&mut transaction, &team_id, 1).await?;

        // Remove team invite
        sqlx::query(
            r#"
            DELETE FROM team_invite
            WHERE id = $1
            "#,
        )
        .bind(team_invite_id)
        .execute(&mut *transaction)
        .await?;

        transaction.commit().await?;

        let member = TeamMember {
            user_id: MacroUserIdStr::parse_from_str(
                team_member.try_get::<String, _>("user_id")?.as_str(),
            )
            .map(|id| id.into_owned())
            .map_err(|e| TeamError::StorageLayerError(e.into()))?,
            role: team_member.try_get("team_role")?,
            plan: team_member.try_get("plan")?,
            team_id,
        };

        Ok(AcceptedTeamInvite {
            member,
            invite: invite_snapshot,
        })
    }

    #[tracing::instrument(skip(self), err)]
    #[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
    async fn rollback_accept_team_invite(
        &self,
        accepted_invite: &AcceptedTeamInvite<'_>,
    ) -> Result<(), TeamError> {
        let mut transaction = self.pool.begin().await?;

        let deleted = sqlx::query(
            r#"
            DELETE FROM team_user
            WHERE team_id = $1 AND user_id = $2
            "#,
        )
        .bind(accepted_invite.member.team_id)
        .bind(accepted_invite.member.user_id.as_ref())
        .execute(&mut *transaction)
        .await?;

        if deleted.rows_affected() > 0 {
            TeamRepositoryImpl::bump_seat_count(
                &mut transaction,
                &accepted_invite.member.team_id,
                -1,
            )
            .await?;
        }

        sqlx::query(
            r#"
            INSERT INTO team_invite
                (id, team_id, email, team_role, invited_by, created_at, last_sent_at, is_agent)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            ON CONFLICT DO NOTHING
            "#,
        )
        .bind(accepted_invite.invite.id)
        .bind(accepted_invite.invite.team_id)
        .bind(accepted_invite.invite.email.as_ref())
        .bind(accepted_invite.invite.team_role)
        .bind(accepted_invite.invite.invited_by.as_ref())
        .bind(accepted_invite.invite.created_at.naive_utc())
        .bind(accepted_invite.invite.last_sent_at.naive_utc())
        .bind(accepted_invite.invite.is_agent)
        .execute(&mut *transaction)
        .await?;

        transaction.commit().await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    #[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
    async fn rollback_remove_user_from_team(
        &self,
        removed_member: &TeamMember<'_>,
    ) -> Result<(), TeamError> {
        let mut transaction = self.pool.begin().await?;

        let inserted = sqlx::query(
            r#"
            INSERT INTO team_user (team_id, user_id, team_role, plan)
            VALUES ($1, $2, $3, $4)
            ON CONFLICT DO NOTHING
            "#,
        )
        .bind(removed_member.team_id)
        .bind(removed_member.user_id.as_ref())
        .bind(removed_member.role)
        .bind(removed_member.plan)
        .execute(&mut *transaction)
        .await?;

        if inserted.rows_affected() > 0 {
            TeamRepositoryImpl::bump_seat_count(&mut transaction, &removed_member.team_id, 1)
                .await?;
        }

        transaction.commit().await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn is_user_member_of_team(
        &self,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<bool, TeamError> {
        let team_member: Option<()> = sqlx::query!(
            r#"
            SELECT team_id FROM team_user
            WHERE user_id = $1
            "#,
            user_id.as_ref(),
        )
        .map(|_| ())
        .fetch_optional(&self.pool)
        .await?;

        Ok(team_member.is_some())
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_members(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<Vec<TeamMember<'_>>, TeamError> {
        let members = sqlx::query!(
            r#"
            SELECT user_id, 
                team_role as "team_role!: TeamRole",
                plan as "plan!: SeatPlan"
            FROM team_user
            WHERE team_id = $1
            "#,
            team_id,
        )
        .fetch_all(&self.pool)
        .await?;

        let members: Vec<Result<TeamMember, anyhow::Error>> = members
            .into_iter()
            .map(|row| {
                let user_id =
                    MacroUserIdStr::parse_from_str(&row.user_id).map(|id| id.into_owned());

                if let Ok(user_id) = user_id {
                    Ok(TeamMember {
                        user_id,
                        role: row.team_role,
                        plan: row.plan,
                        team_id: *team_id,
                    })
                } else {
                    Err(anyhow::anyhow!("unable to parse user id"))
                }
            })
            .collect();

        let members = members
            .into_iter()
            .filter_map(|member| member.ok())
            .collect();

        Ok(members)
    }

    #[tracing::instrument(skip(self), err)]
    async fn bulk_is_member_of_other_team(
        &self,
        ignore_team_ids: non_empty::NonEmpty<&[uuid::Uuid]>,
        users: non_empty::NonEmpty<&[MacroUserIdStr<'_>]>,
    ) -> Result<Vec<MacroUserIdStr<'_>>, TeamError> {
        let result = sqlx::query!(
            r#"
            SELECT user_id
            FROM team_user
            WHERE user_id = ANY($1::text[])
            AND team_id NOT IN (
            SELECT * FROM UNNEST($2::uuid[])
            )
            AND team_role NOT IN ('owner')
            "#,
            &users
                .as_ref()
                .iter()
                .map(|u| u.as_ref().to_string())
                .collect::<Vec<_>>(),
            ignore_team_ids.as_ref(),
        )
        .fetch_all(&self.pool)
        .await?;

        let members: Vec<Result<_, _>> = result
            .into_iter()
            .map(|row| MacroUserIdStr::parse_from_str(&row.user_id).map(|id| id.into_owned()))
            .collect();

        let members = members
            .into_iter()
            .filter_map(|member| member.ok())
            .collect();

        Ok(members)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_by_id(&self, team_id: &uuid::Uuid) -> Result<TeamWithMembers, TeamError> {
        let team = sqlx::query!(
            r#"
            SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,
                t.allow_non_admin_invites,
                t.default_link_share as "default_link_share: LinkShare",
                t.language as "language: Language",
                COALESCE(tcs.crm_enabled, FALSE) AS "crm_enabled!"
            FROM team t
            LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id
            WHERE t.id = $1
            "#,
            team_id,
        )
        .try_map(|row| {
            Ok(Team {
                id: row.id,
                name: row.name,
                slug: row.slug,
                owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)
                    .map_err(type_err)?
                    .into_owned(),
                crm_enabled: row.crm_enabled,
                auto_join_domain: row.auto_join_domain,
                enterprise: row.enterprise,
                allow_non_admin_invites: row.allow_non_admin_invites,
                default_link_share: row.default_link_share,
                language: row.language,
            })
        })
        .fetch_one(&self.pool)
        .await?;

        let members = sqlx::query!(
            r#"
            SELECT user_id,
                team_role as "team_role!: TeamRole",
                plan as "plan!: SeatPlan"
            FROM team_user
            WHERE team_id = $1
            "#,
            team_id,
        )
        .fetch_all(&self.pool)
        .await?;

        let members = members
            .into_iter()
            .filter_map(|row| {
                MacroUserIdStr::parse_from_str(&row.user_id)
                    .map(|id| TeamMember {
                        user_id: id.into_owned(),
                        role: row.team_role,
                        plan: row.plan,
                        team_id: *team_id,
                    })
                    .ok()
            })
            .collect();

        Ok(TeamWithMembers {
            team,
            members,
            scheduled_seat_plans: None,
        })
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_user_teams(&self, user_id: &MacroUserIdStr<'_>) -> Result<Vec<Team>, TeamError> {
        let teams = sqlx::query!(
            r#"
            SELECT t.id, t.name, t.slug, t.owner_id, t.auto_join_domain, t.enterprise,
                t.allow_non_admin_invites,
                t.default_link_share as "default_link_share: LinkShare",
                t.language as "language: Language",
                COALESCE(tcs.crm_enabled, FALSE) AS "crm_enabled!"
            FROM team t
            JOIN team_user tu ON t.id = tu.team_id
            LEFT JOIN team_crm_settings tcs ON tcs.team_id = t.id
            WHERE tu.user_id = $1
            "#,
            user_id.as_ref(),
        )
        .try_map(|row| {
            Ok(Team {
                id: row.id,
                name: row.name,
                slug: row.slug,
                owner_id: MacroUserIdStr::parse_from_str(&row.owner_id)
                    .map_err(type_err)?
                    .into_owned(),
                crm_enabled: row.crm_enabled,
                auto_join_domain: row.auto_join_domain,
                enterprise: row.enterprise,
                allow_non_admin_invites: row.allow_non_admin_invites,
                default_link_share: row.default_link_share,
                language: row.language,
            })
        })
        .fetch_all(&self.pool)
        .await?;

        Ok(teams)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_user_team_invites(
        &self,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<Vec<TeamInviteDetails>, TeamError> {
        let email = user_id.email_part().lowercase();

        let invites = sqlx::query!(
            r#"
            SELECT
                id,
                email,
                team_id,
                team_role as "team_role!: TeamRole",
                invited_by,
                created_at as "created_at!: chrono::DateTime<chrono::Utc>",
                last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>",
                is_agent
            FROM team_invite
            WHERE email = $1
            "#,
            email.as_ref(),
        )
        .map(|row| TeamInviteDetails {
            id: row.id,
            email: row.email,
            team_id: row.team_id,
            team_role: row.team_role,
            invited_by: row.invited_by,
            created_at: row.created_at,
            last_sent_at: row.last_sent_at,
            is_agent: row.is_agent,
        })
        .fetch_all(&self.pool)
        .await?;

        Ok(invites)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_invites(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<Vec<TeamInviteDetails>, TeamError> {
        let invites = sqlx::query!(
            r#"
            SELECT
                id,
                email,
                team_id,
                team_role as "team_role!: TeamRole",
                invited_by,
                created_at as "created_at!: chrono::DateTime<chrono::Utc>",
                last_sent_at as "last_sent_at!: chrono::DateTime<chrono::Utc>",
                is_agent
            FROM team_invite
            WHERE team_id = $1
            "#,
            team_id,
        )
        .map(|row| TeamInviteDetails {
            id: row.id,
            email: row.email,
            team_id: row.team_id,
            team_role: row.team_role,
            invited_by: row.invited_by,
            created_at: row.created_at,
            last_sent_at: row.last_sent_at,
            is_agent: row.is_agent,
        })
        .fetch_all(&self.pool)
        .await?;

        Ok(invites)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_name(&self, team_id: &uuid::Uuid) -> Result<String, TeamError> {
        let name = sqlx::query!(
            r#"
            SELECT name
            FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .map(|row| row.name)
        .fetch_one(&self.pool)
        .await?;

        Ok(name)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_user_display_name(
        &self,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<Option<String>, TeamError> {
        let row = sqlx::query!(
            r#"
            SELECT
                NULLIF(mui.first_name,  'N/A') AS first_name,
                NULLIF(mui.last_name,   'N/A') AS last_name
            FROM macro_user_info mui
            JOIN "User" u ON mui.macro_user_id = u.macro_user_id
            WHERE u.id = $1
            LIMIT 1
            "#,
            user_id.as_ref(),
        )
        .fetch_optional(&self.pool)
        .await?;

        Ok(row.and_then(|row| match (row.first_name, row.last_name) {
            (None, None) => None,
            (Some(name), None) | (None, Some(name)) => Some(name),
            (Some(first), Some(last)) => Some(format!("{first} {last}")),
        }))
    }

    #[tracing::instrument(skip(self), err)]
    async fn patch_team(
        &self,
        team_id: &uuid::Uuid,
        req: &PatchTeamRequest,
    ) -> Result<(), TeamError> {
        let normalized_slug = req.slug.as_deref().map(normalize_team_slug).transpose()?;

        // default_link_share needs a separate "provided" flag: NULL is a
        // meaningful new value (link sharing off), so COALESCE can't express
        // "keep".
        let default_link_share_provided = req.default_link_share.is_some();
        let default_link_share = req.default_link_share.flatten();
        // Same for language: NULL lets each member's browser decide.
        let language_provided = req.language.is_some();
        let language = req.language.flatten();

        if req.name.is_some()
            || normalized_slug.is_some()
            || default_link_share_provided
            || language_provided
        {
            let result = sqlx::query!(
                r#"
                UPDATE team
                SET
                    name = COALESCE($2, name),
                    slug = COALESCE($3, slug),
                    default_link_share = CASE WHEN $4 THEN $5 ELSE default_link_share END,
                    language = CASE WHEN $6 THEN $7 ELSE language END
                WHERE id = $1
                "#,
                team_id,
                req.name.as_deref(),
                normalized_slug.as_deref(),
                default_link_share_provided,
                default_link_share as Option<LinkShare>,
                language_provided,
                language as Option<Language>,
            )
            .execute(&self.pool)
            .await?;

            if result.rows_affected() == 0 {
                return Err(TeamError::TeamDoesNotExist);
            }
        }

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_role(
        &self,
        team_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<Option<TeamRole>, TeamError> {
        let team_role = sqlx::query!(
            r#"
            SELECT team_role as "team_role!: TeamRole"
            FROM team_user
            WHERE team_id = $1 AND user_id = $2
            "#,
            team_id,
            user_id.as_ref(),
        )
        .map(|r| r.team_role)
        .fetch_optional(&self.pool)
        .await?;

        Ok(team_role)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_member(
        &self,
        team_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<TeamMember<'_>, TeamError> {
        let member = sqlx::query!(
            r#"
            SELECT user_id, 
                team_role as "team_role!: TeamRole",
                plan as "plan!: SeatPlan"
            FROM team_user
            WHERE team_id = $1
            AND user_id = $2
            "#,
            team_id,
            user_id.as_ref(),
        )
        .try_map(|r| {
            Ok(TeamMember {
                user_id: MacroUserIdStr::parse_from_str(&r.user_id)
                    .map_err(type_err)?
                    .into_owned(),
                team_id: *team_id,
                role: r.team_role,
                plan: r.plan,
            })
        })
        .fetch_one(&self.pool)
        .await?;

        Ok(member)
    }

    #[tracing::instrument(skip(self), err)]
    async fn patch_team_user_role(
        &self,
        team_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
        team_role: TeamRole,
    ) -> Result<(), TeamError> {
        let result = sqlx::query!(
            r#"
            UPDATE team_user
            SET team_role = $3
            WHERE team_id = $1
            AND user_id = $2
            "#,
            team_id,
            user_id.as_ref(),
            team_role as _,
        )
        .execute(&self.pool)
        .await?;

        if result.rows_affected() == 0 {
            return Err(TeamError::TeamMemberNotFound(*team_id));
        }

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn patch_team_member_plan(
        &self,
        team_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
        plan: SeatPlan,
    ) -> Result<(), TeamError> {
        let result = sqlx::query!(
            r#"
            UPDATE team_user
            SET plan = $3
            WHERE team_id = $1
            AND user_id = $2
            "#,
            team_id,
            user_id.as_ref(),
            plan as _,
        )
        .execute(&self.pool)
        .await?;

        if result.rows_affected() == 0 {
            return Err(TeamError::TeamMemberNotFound(*team_id));
        }

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_seat_count(&self, team_id: &uuid::Uuid) -> Result<i32, TeamError> {
        let seat_count = sqlx::query!(
            r#"
            SELECT seat_count
            FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .map(|row| row.seat_count)
        .fetch_one(&self.pool)
        .await?;

        Ok(seat_count)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_plan(&self, team_id: &uuid::Uuid) -> Result<Option<TeamPlan>, TeamError> {
        let plan = sqlx::query!(
            r#"
            SELECT plan as "plan?: TeamPlan"
            FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .map(|row| row.plan)
        .fetch_one(&self.pool)
        .await?;

        Ok(plan)
    }

    #[tracing::instrument(skip(self), err)]
    async fn patch_team_plan(
        &self,
        team_id: &uuid::Uuid,
        team_plan: TeamPlan,
    ) -> Result<(), TeamError> {
        let result = sqlx::query!(
            r#"
            UPDATE team
            SET plan = $2
            WHERE id = $1
            "#,
            team_id,
            team_plan as _,
        )
        .execute(&self.pool)
        .await?;

        if result.rows_affected() == 0 {
            return Err(TeamError::TeamDoesNotExist);
        }

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn toggle_auto_join_domain(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<Option<String>, ToggleAutoJoinDomainError> {
        let mut transaction = self.pool.begin().await.map_err(TeamError::from)?;

        // Lock the row so concurrent toggles serialize instead of both
        // reading the same current value.
        let team = sqlx::query!(
            r#"
            SELECT auto_join_domain, owner_id
            FROM team
            WHERE id = $1
            FOR UPDATE
            "#,
            team_id,
        )
        .fetch_one(&mut *transaction)
        .await?;

        let new_domain = if team.auto_join_domain.is_some() {
            None
        } else {
            let owner_id = MacroUserIdStr::parse_from_str(&team.owner_id)
                .map_err(|e| TeamError::StorageLayerError(e.into()))?;
            let owner_email = owner_id.email_part().lowercase();
            let domain = owner_email.domain_part();

            if is_generic_email_domain(domain) {
                return Err(ToggleAutoJoinDomainError::GenericDomainNotAllowed(
                    domain.to_owned(),
                ));
            }

            Some(domain.to_owned())
        };

        sqlx::query!(
            r#"
            UPDATE team
            SET auto_join_domain = $2
            WHERE id = $1
            "#,
            team_id,
            new_domain.as_deref(),
        )
        .execute(&mut *transaction)
        .await?;

        transaction.commit().await.map_err(TeamError::from)?;

        Ok(new_domain)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_invite_link(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<Option<TeamInviteLinkToken>, TeamError> {
        invite_link::get_team_invite_link(&self.pool, team_id).await
    }

    #[tracing::instrument(skip(self, token), err)]
    async fn set_team_invite_link(
        &self,
        team_id: &uuid::Uuid,
        token: &TeamInviteLinkToken,
        created_by: &MacroUserIdStr<'_>,
    ) -> Result<(), TeamError> {
        invite_link::set_team_invite_link(&self.pool, team_id, token, created_by).await
    }

    #[tracing::instrument(skip(self, token), err)]
    async fn get_team_invite_link_creator(
        &self,
        token: &TeamInviteLinkToken,
    ) -> Result<Option<MacroUserIdStr<'static>>, TeamError> {
        invite_link::get_team_invite_link_creator(&self.pool, token).await
    }

    #[tracing::instrument(skip(self), err)]
    async fn delete_team_invite_link(&self, team_id: &uuid::Uuid) -> Result<(), TeamError> {
        invite_link::delete_team_invite_link(&self.pool, team_id).await
    }

    #[tracing::instrument(skip(self, token), err)]
    async fn get_team_by_invite_link(
        &self,
        token: &TeamInviteLinkToken,
    ) -> Result<Option<TeamInviteLinkTeam>, TeamError> {
        invite_link::get_team_by_invite_link(&self.pool, token).await
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_allow_non_admin_invites(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<bool, TeamError> {
        sqlx::query_scalar!(
            r#"
            SELECT allow_non_admin_invites
            FROM team
            WHERE id = $1
            "#,
            team_id,
        )
        .fetch_optional(&self.pool)
        .await?
        .ok_or(TeamError::TeamDoesNotExist)
    }

    #[tracing::instrument(skip(self), err)]
    async fn toggle_allow_non_admin_invites(
        &self,
        team_id: &uuid::Uuid,
    ) -> Result<bool, TeamError> {
        sqlx::query_scalar!(
            r#"
            UPDATE team
            SET allow_non_admin_invites = NOT allow_non_admin_invites
            WHERE id = $1
            RETURNING allow_non_admin_invites
            "#,
            team_id,
        )
        .fetch_optional(&self.pool)
        .await?
        .ok_or(TeamError::TeamDoesNotExist)
    }

    #[tracing::instrument(skip(self), err)]
    async fn add_user_to_team(
        &self,
        team_id: &uuid::Uuid,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<Option<TeamMember<'static>>, TeamError> {
        let mut transaction = self.pool.begin().await?;

        let inserted = sqlx::query!(
            r#"
            INSERT INTO team_user (team_id, user_id, team_role)
            VALUES ($1, $2, 'member')
            ON CONFLICT DO NOTHING
            "#,
            team_id,
            user_id.as_ref(),
        )
        .execute(&mut *transaction)
        .await?;

        // Already a member — nothing was added, so don't touch the invite or seat count.
        if inserted.rows_affected() == 0 {
            return Ok(None);
        }

        let user_email = user_id.email_part().lowercase();
        sqlx::query!(
            r#"
            DELETE FROM team_invite
            WHERE team_id = $1 AND email = $2
            "#,
            team_id,
            user_email.as_ref(),
        )
        .execute(&mut *transaction)
        .await?;

        TeamRepositoryImpl::bump_seat_count(&mut transaction, team_id, 1).await?;

        transaction.commit().await?;

        Ok(Some(TeamMember {
            team_id: *team_id,
            user_id: user_id.clone().into_owned(),
            role: TeamRole::Member,
            plan: SeatPlan::Premium,
        }))
    }

    #[tracing::instrument(skip(self), err)]
    async fn list_team_ids_after(
        &self,
        after_team_id: Option<uuid::Uuid>,
        limit: u32,
    ) -> Result<Vec<uuid::Uuid>, TeamError> {
        Ok(sqlx::query_scalar!(
            r#"
            SELECT id
            FROM team
            WHERE $1::uuid IS NULL OR id > $1
            ORDER BY id
            LIMIT $2
            "#,
            after_team_id,
            i64::from(limit),
        )
        .fetch_all(&self.pool)
        .await?)
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_team_id_by_domain(
        &self,
        user_id: &MacroUserIdStr<'_>,
    ) -> Result<Option<uuid::Uuid>, TeamError> {
        let user_email = user_id.email_part().lowercase();
        let domain = user_email.domain_part();

        // Uses the partial index on auto_join_domain; when several teams
        // claim the same domain, pick the oldest (ids are UUIDv7).
        let team_id = sqlx::query_scalar!(
            r#"
            SELECT id
            FROM team
            WHERE auto_join_domain = $1
            ORDER BY id
            LIMIT 1
            "#,
            domain,
        )
        .fetch_optional(&self.pool)
        .await?;

        Ok(team_id)
    }
}