Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

36.5 KB
Raw Blame
//! Entity property endpoints.
//!
//! Access control happens in the receipt extractors ([`super::extract`]): the
//! handlers receive a minted [`ViewReceipt`](crate::domain::model::ViewReceipt)
//! or [`EditReceipt`](crate::domain::model::EditReceipt) and pass it into the
//! service, whose entity-scoped methods only accept receipts.

use std::collections::HashMap;

use axum::{
    Json,
    extract::{Path, Query, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use entity_access::domain::models::EditAccessLevel;
use entity_access::domain::ports::EntityAccessService;
use macro_authorization::{MacroAuthorizationExtractor, MacroAuthorizationService, UserOrInternal};
use models_properties::api::{PropertyTargetEntityType, PropertyTargetReference, SetPropertyValue};
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use utoipa::ToSchema;
use uuid::Uuid;

use super::extract::{EditReceiptExtractor, ViewReceiptExtractor};
use super::extract::{mint_authenticated_receipt, mint_view_receipt, target_entity_type};
use super::{PropertiesRouterState, properties_err_status};
use crate::domain::error::PropertiesErr;
use crate::domain::model::PropertyAccessReceiptExt;
use crate::domain::model::{EditReceipt, EntityOptionUpdateOutcome, EntityPropertyOptionUpdate};
use crate::domain::service::PropertiesService;

#[cfg(test)]
mod test;

// Re-export EntityQueryParams from models_properties for convenience
pub use models_properties::api::EntityQueryParams;

/// Response for document/entity properties endpoint.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct EntityPropertiesResponse {
    pub entity_id: String,
    pub properties: Vec<EntityPropertyWithDefinition>,
}

/// Type-safe request for setting entity property values.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct SetEntityPropertyRequest {
    /// The value to set for the property. If None, the property is attached to the entity without a value.
    #[serde(default)]
    pub value: Option<SetPropertyValue>,
}

/// Request for getting properties for multiple entities in bulk
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BulkEntityPropertiesRequest {
    /// Array of entity references (entity_id and entity_type pairs)
    pub entities: Vec<PropertyTargetReference>,
    /// Optional: only return properties with these definition IDs. If empty, returns all.
    #[serde(default)]
    pub property_ids: Vec<Uuid>,
}

/// Maximum number of entities allowed in a single bulk properties request.
const MAX_BULK_ENTITIES: usize = 200;
/// Maximum number of property IDs allowed in a single bulk properties request.
const MAX_BULK_PROPERTY_IDS: usize = 200;

#[derive(Debug, Error)]
pub enum GetEntityPropertiesErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),

    #[error("Entity not found")]
    MetadataNotFound,
}

impl IntoResponse for GetEntityPropertiesErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            GetEntityPropertiesErr::Properties(e) => properties_err_status(e),
            // Preserved behavior: a missing entity on the metadata path is a 500.
            GetEntityPropertiesErr::MetadataNotFound => StatusCode::INTERNAL_SERVER_ERROR,
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "GetEntityPropertiesErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Get all properties for an entity
#[utoipa::path(
    get,
    path = "/properties/entities/{entity_type}/{entity_id}",
    params(
        ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),
        ("entity_id" = String, Path, description = "Entity ID"),
        ("include_metadata" = Option<bool>, Query, description = "Whether to include property metadata (default: false)")
    ),
    responses(
        (status = 200, description = "Entity properties retrieved successfully", body = EntityPropertiesResponse),
        (status = 400, description = "Invalid entity type"),
        (status = 403, description = "Forbidden - User does not have permission to view this entity"),
        (status = 404, description = "Entity not found"),
        (status = 500, description = "Internal server error")
    ),
    tag = "Properties"
)]
#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type(), include_metadata = query.include_metadata), err)]
pub async fn get_entity_properties<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    Query(query): Query<EntityQueryParams>,
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    // Anonymous access is allowed for publicly shared entities; the extractor
    // minted a view receipt either way.
    access: ViewReceiptExtractor,
) -> Result<Json<EntityPropertiesResponse>, GetEntityPropertiesErr> {
    let ViewReceiptExtractor(access) = access;
    tracing::info!("retrieving entity properties");

    let (user_properties, metadata_properties) = if query.include_metadata {
        // Fetch user properties and metadata in parallel when metadata is requested
        let (user_properties_result, metadata_properties_result) = tokio::join!(
            state
                .properties_service
                .get_entity_properties_with_definitions(&access),
            state
                .properties_service
                .get_entity_metadata_properties(&access)
        );

        let user_properties = user_properties_result?;
        let metadata_properties =
            metadata_properties_result?.ok_or(GetEntityPropertiesErr::MetadataNotFound)?;

        (user_properties, metadata_properties)
    } else {
        // Only fetch user properties when metadata not requested - no parallel task needed
        tracing::debug!("skipping metadata properties due to include_metadata=false");
        let user_properties = state
            .properties_service
            .get_entity_properties_with_definitions(&access)
            .await?;

        (user_properties, vec![])
    };

    let mut all_properties = user_properties;
    all_properties.extend(metadata_properties);

    let response = EntityPropertiesResponse {
        entity_id: access.entity_id().to_string(),
        properties: all_properties,
    };

    tracing::info!(
        properties_count = response.properties.len(),
        "successfully retrieved entity properties"
    );

    Ok(Json(response))
}

#[derive(Debug, Error)]
pub enum GetBulkEntityPropertiesErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),
    #[error("Entities array cannot be empty")]
    InvalidRequest,
    #[error("Cannot request more than {MAX_BULK_ENTITIES} entities at once")]
    TooManyEntities,
    #[error("Cannot request more than {MAX_BULK_PROPERTY_IDS} property IDs at once")]
    TooManyPropertyIds,
}

impl IntoResponse for GetBulkEntityPropertiesErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            GetBulkEntityPropertiesErr::Properties(e) => properties_err_status(e),
            GetBulkEntityPropertiesErr::InvalidRequest
            | GetBulkEntityPropertiesErr::TooManyEntities
            | GetBulkEntityPropertiesErr::TooManyPropertyIds => StatusCode::BAD_REQUEST,
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "GetBulkEntityPropertiesErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Rejects requests whose `entities` or `property_ids` arrays exceed the allowed maximums,
/// before any per-entity permission checks or DB calls are made.
fn validate_bulk_request_size(
    request: &BulkEntityPropertiesRequest,
) -> Result<(), GetBulkEntityPropertiesErr> {
    if request.entities.len() > MAX_BULK_ENTITIES {
        tracing::error!(
            entity_count = request.entities.len(),
            "too many entities in bulk request"
        );
        return Err(GetBulkEntityPropertiesErr::TooManyEntities);
    }
    if request.property_ids.len() > MAX_BULK_PROPERTY_IDS {
        tracing::error!(
            property_id_count = request.property_ids.len(),
            "too many property ids in bulk request"
        );
        return Err(GetBulkEntityPropertiesErr::TooManyPropertyIds);
    }
    Ok(())
}

/// Get properties for multiple entities in bulk (public endpoint with user auth)
///
/// Only returns properties for entities the user has view permission for.
/// Entities without permission are silently omitted from the response.
#[utoipa::path(
    post,
    path = "/properties/entities/bulk",
    request_body = BulkEntityPropertiesRequest,
    responses(
        (status = 200, description = "Bulk entity properties retrieved successfully", body = HashMap<String, EntityPropertiesResponse>),
        (status = 400, description = "Invalid request body"),
        (status = 403, description = "Forbidden - User does not have permission"),
        (status = 500, description = "Internal server error")
    ),
    tag = "Properties"
)]
#[tracing::instrument(skip(state, request, user), fields(entity_count = request.entities.len()), err)]
pub async fn get_bulk_entity_properties<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Json(request): Json<BulkEntityPropertiesRequest>,
) -> Result<Json<HashMap<String, EntityPropertiesResponse>>, GetBulkEntityPropertiesErr> {
    let user = user.authorization.user.macro_user_id;
    // The public endpoint requires explicit property IDs. An empty property_ids
    // means "no properties requested", so return early with empty result.
    if request.entities.is_empty() || request.property_ids.is_empty() {
        return Ok(Json(HashMap::new()));
    }
    validate_bulk_request_size(&request)?;

    // Mint a view receipt per entity, keeping only the entities the user has
    // permission to view.
    let mut receipts = Vec::with_capacity(request.entities.len());
    for entity_ref in &request.entities {
        match mint_view_receipt(
            state.entity_access_service.as_ref(),
            Some(&user),
            &entity_ref.entity_id,
            target_entity_type(entity_ref.entity_type),
        )
        .await
        {
            Ok(receipt) => receipts.push(receipt),
            Err(e) => {
                tracing::debug!(
                    entity_id = %entity_ref.entity_id,
                    entity_type = ?entity_ref.entity_type,
                    error = ?e,
                    "user lacks permission, skipping entity"
                );
            }
        }
    }

    tracing::info!(
        permitted = receipts.len(),
        "filtered entities by permission"
    );

    if receipts.is_empty() {
        return Ok(Json(HashMap::new()));
    }

    let bulk_properties = state
        .properties_service
        .get_bulk_entity_properties(&receipts, request.property_ids)
        .await?;

    let mut result: HashMap<String, EntityPropertiesResponse> = HashMap::new();
    for (key, properties_values) in bulk_properties {
        result.insert(
            key.entity_id.clone(),
            EntityPropertiesResponse {
                entity_id: key.entity_id,
                properties: properties_values,
            },
        );
    }

    tracing::info!(
        successful_entities = result.len(),
        "successfully retrieved bulk entity properties"
    );

    Ok(Json(result))
}

#[derive(Debug, Error)]
pub enum SetEntityPropertyErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),
}

impl IntoResponse for SetEntityPropertyErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            SetEntityPropertyErr::Properties(e) => properties_err_status(e),
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "SetEntityPropertyErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Set or update a property value for an entity, or attach a property without a value
#[utoipa::path(
    put,
    path = "/properties/entities/{entity_type}/{entity_id}/{property_id}",
    params(
        ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),
        ("entity_id" = String, Path, description = "Entity ID"),
        ("property_id" = Uuid, Path, description = "Property ID")
    ),
    request_body = SetEntityPropertyRequest,
    responses(
        (status = 204, description = "Entity property set successfully (with or without value)"),
        (status = 400, description = "Invalid request or entity type"),
        (status = 403, description = "No edit access to the entity"),
        (status = 404, description = "Entity or property not found"),
        (status = 500, description = "Internal server error")
    ),
    tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access, request), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, entity_type = ?access.0.entity_type(), has_value = request.value.is_some()), err)]
pub async fn set_entity_property<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    Path((_entity_type, _entity_id, property_uuid)): Path<(PropertyTargetEntityType, String, Uuid)>,
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    access: EditReceiptExtractor,
    Json(request): Json<SetEntityPropertyRequest>,
) -> Result<StatusCode, SetEntityPropertyErr> {
    tracing::info!("setting entity property");

    state
        .properties_service
        .set_entity_property(&access.0, property_uuid, request.value)
        .await?;

    tracing::info!("successfully set entity property");

    Ok(StatusCode::NO_CONTENT)
}

#[derive(Debug, Error)]
pub enum EntityPropertyOptionErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),
}

impl IntoResponse for EntityPropertyOptionErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            EntityPropertyOptionErr::Properties(e) => properties_err_status(e),
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "EntityPropertyOptionErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Add a single option to an entity's multi-select property value.
///
/// Atomic delta: the option is appended to the current stored value (deduped,
/// attaching the property if needed), so concurrent edits to the same value
/// merge rather than overwrite each other. Prefer this over the full-value PUT
/// when adding one option.
#[utoipa::path(
    post,
    path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",
    params(
        ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),
        ("entity_id" = String, Path, description = "Entity ID"),
        ("property_id" = Uuid, Path, description = "Property ID"),
        ("option_id" = Uuid, Path, description = "Option ID to add")
    ),
    responses(
        (status = 204, description = "Option added successfully"),
        (status = 400, description = "Invalid request, property is not multi-select, or option does not belong to the property"),
        (status = 403, description = "No edit access to the entity"),
        (status = 500, description = "Internal server error")
    ),
    tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]
pub async fn add_entity_property_option<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(
        PropertyTargetEntityType,
        String,
        Uuid,
        Uuid,
    )>,
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    access: EditReceiptExtractor,
) -> Result<StatusCode, EntityPropertyOptionErr> {
    tracing::info!("adding entity property option");

    state
        .properties_service
        .add_entity_property_option(&access.0, property_uuid, option_uuid)
        .await?;

    Ok(StatusCode::NO_CONTENT)
}

/// Remove a single option from an entity's multi-select property value.
///
/// Atomic delta: the option is stripped from the current stored value (a no-op
/// if absent), so concurrent edits to the same value merge rather than overwrite
/// each other.
#[utoipa::path(
    delete,
    path = "/properties/entities/{entity_type}/{entity_id}/{property_id}/options/{option_id}",
    params(
        ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),
        ("entity_id" = String, Path, description = "Entity ID"),
        ("property_id" = Uuid, Path, description = "Property ID"),
        ("option_id" = Uuid, Path, description = "Option ID to remove")
    ),
    responses(
        (status = 204, description = "Option removed successfully"),
        (status = 403, description = "No edit access to the entity"),
        (status = 500, description = "Internal server error")
    ),
    tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), property_id = %property_uuid, option_id = %option_uuid, entity_type = ?access.0.entity_type()), err)]
pub async fn remove_entity_property_option<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    Path((_entity_type, _entity_id, property_uuid, option_uuid)): Path<(
        PropertyTargetEntityType,
        String,
        Uuid,
        Uuid,
    )>,
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    access: EditReceiptExtractor,
) -> Result<StatusCode, EntityPropertyOptionErr> {
    tracing::info!("removing entity property option");

    state
        .properties_service
        .remove_entity_property_option(&access.0, property_uuid, option_uuid)
        .await?;

    Ok(StatusCode::NO_CONTENT)
}

/// One property's option changes in a bulk selection update. The change is a
/// delta (options to add / remove) so it composes with concurrent edits rather
/// than replacing the whole value.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct EntityPropertyOptionUpdateRequest {
    /// The multi-select property definition being changed.
    pub property_id: Uuid,
    /// Options to add (deduped against the current value).
    #[serde(default)]
    pub add_option_ids: Vec<Uuid>,
    /// Options to remove (a no-op if not present).
    #[serde(default)]
    pub remove_option_ids: Vec<Uuid>,
}

/// Request to apply option deltas across one or more of an entity's multi-select
/// properties in a single transaction.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BulkUpdateEntityPropertyOptionsRequest {
    /// The per-property option changes to apply.
    pub properties: Vec<EntityPropertyOptionUpdateRequest>,
}

/// The reconciled final option ids stored for one property after a bulk update.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct EntityPropertyOptionSelectionResponse {
    /// The property definition the options belong to.
    pub property_id: Uuid,
    /// The final option ids the server persisted, in stored order.
    pub option_ids: Vec<Uuid>,
}

/// Response for a bulk option update: each property's reconciled final ids.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BulkUpdateEntityPropertyOptionsResponse {
    /// The final option ids per updated property.
    pub properties: Vec<EntityPropertyOptionSelectionResponse>,
}

/// Maximum properties changeable in one bulk option request.
const MAX_BULK_OPTION_PROPERTIES: usize = 100;
/// Maximum option ids (added plus removed) per property in one bulk request.
const MAX_OPTION_IDS_PER_PROPERTY: usize = 500;

#[derive(Debug, Error)]
pub enum BulkUpdateEntityPropertyOptionsErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),
    #[error("Duplicate property id in request")]
    DuplicateProperty,
    #[error("Cannot update more than {MAX_BULK_OPTION_PROPERTIES} properties at once")]
    TooManyProperties,
    #[error("Cannot change more than {MAX_OPTION_IDS_PER_PROPERTY} options for a property at once")]
    TooManyOptions,
}

impl IntoResponse for BulkUpdateEntityPropertyOptionsErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            BulkUpdateEntityPropertyOptionsErr::Properties(e) => properties_err_status(e),
            BulkUpdateEntityPropertyOptionsErr::DuplicateProperty
            | BulkUpdateEntityPropertyOptionsErr::TooManyProperties
            | BulkUpdateEntityPropertyOptionsErr::TooManyOptions => StatusCode::BAD_REQUEST,
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "BulkUpdateEntityPropertyOptionsErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Reject oversized or duplicate-property requests before any database work, so
/// one authenticated call can't force unbounded query and lock work.
fn validate_bulk_option_request(
    request: &BulkUpdateEntityPropertyOptionsRequest,
) -> Result<(), BulkUpdateEntityPropertyOptionsErr> {
    if request.properties.len() > MAX_BULK_OPTION_PROPERTIES {
        return Err(BulkUpdateEntityPropertyOptionsErr::TooManyProperties);
    }
    let mut seen = std::collections::HashSet::with_capacity(request.properties.len());
    for property in &request.properties {
        if !seen.insert(property.property_id) {
            return Err(BulkUpdateEntityPropertyOptionsErr::DuplicateProperty);
        }
        if property.add_option_ids.len() + property.remove_option_ids.len()
            > MAX_OPTION_IDS_PER_PROPERTY
        {
            return Err(BulkUpdateEntityPropertyOptionsErr::TooManyOptions);
        }
    }
    Ok(())
}

/// Apply a complete tag-picker selection across an entity's multi-select
/// properties in one request.
///
/// Each property change is expressed as an option delta and applied to the
/// current stored value under a per-row lock inside a single transaction, so the
/// selection persists atomically and composes with concurrent edits instead of
/// clobbering them. Returns the reconciled final option ids per property for
/// cache reconciliation.
#[utoipa::path(
    post,
    path = "/properties/entities/{entity_type}/{entity_id}/options/bulk",
    params(
        ("entity_type" = PropertyTargetEntityType, Path, description = "Canonical entity type; tasks use DOCUMENT"),
        ("entity_id" = String, Path, description = "Entity ID")
    ),
    request_body = BulkUpdateEntityPropertyOptionsRequest,
    responses(
        (status = 200, description = "Options updated; returns final ids per property", body = BulkUpdateEntityPropertyOptionsResponse),
        (status = 400, description = "Invalid request, a property is not multi-select, or an option does not belong to its property"),
        (status = 403, description = "No edit access to the entity"),
        (status = 500, description = "Internal server error")
    ),
    tags = ["Properties"]
)]
#[tracing::instrument(skip(state, access, request), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type(), property_count = request.properties.len()), err)]
pub async fn bulk_update_entity_property_options<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    access: EditReceiptExtractor,
    Json(request): Json<BulkUpdateEntityPropertyOptionsRequest>,
) -> Result<Json<BulkUpdateEntityPropertyOptionsResponse>, BulkUpdateEntityPropertyOptionsErr> {
    tracing::info!("bulk updating entity property options");

    validate_bulk_option_request(&request)?;

    let updates = request
        .properties
        .into_iter()
        .map(|property| EntityPropertyOptionUpdate {
            property_definition_id: property.property_id,
            add_option_ids: property.add_option_ids,
            remove_option_ids: property.remove_option_ids,
        })
        .collect();

    let selections = state
        .properties_service
        .bulk_update_entity_property_options(&access.0, updates)
        .await?;

    Ok(Json(BulkUpdateEntityPropertyOptionsResponse {
        properties: selections
            .into_iter()
            .map(|selection| EntityPropertyOptionSelectionResponse {
                property_id: selection.property_definition_id,
                option_ids: selection.option_ids,
            })
            .collect(),
    }))
}

/// Request to apply one shared option delta across several entities in a single
/// call. Mirrors the per-entity bulk endpoint's delta semantics, applied to
/// every listed entity (e.g. tag N emails with one label in one request).
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BulkUpdateEntitiesPropertyOptionsRequest {
    /// The entities to update. Entities the caller cannot edit are skipped.
    pub entities: Vec<PropertyTargetReference>,
    /// The multi-select property definition changed on every entity.
    pub property_id: Uuid,
    /// Options to add to each entity's current value (deduped).
    #[serde(default)]
    pub add_option_ids: Vec<Uuid>,
    /// Options to remove from each entity's current value (a no-op if absent).
    #[serde(default)]
    pub remove_option_ids: Vec<Uuid>,
}

/// Per-entity outcome of a cross-entity bulk option update.
#[derive(Debug, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BulkEntityOptionUpdateStatus {
    /// The delta was applied to the entity.
    Applied,
    /// The caller lacks edit access to the entity; it was left unchanged.
    SkippedNoPermission,
    /// The delta could not be applied (wrong entity type, or a write failure).
    Failed,
}

/// One entity's result in a cross-entity bulk option update.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BulkEntityOptionUpdateResult {
    /// The entity's type this result is for.
    pub entity_type: PropertyTargetEntityType,
    /// The entity's id this result is for.
    pub entity_id: String,
    /// Whether the delta was applied, skipped, or failed for this entity.
    pub status: BulkEntityOptionUpdateStatus,
    /// The entity's reconciled final option ids, present only when `applied`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub option_ids: Option<Vec<Uuid>>,
    /// A human-readable reason, present only when `failed`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Response for a cross-entity bulk option update: one result per requested
/// entity, in request order.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct BulkUpdateEntitiesPropertyOptionsResponse {
    /// Per-entity results, aligned to the request's `entities` order.
    pub results: Vec<BulkEntityOptionUpdateResult>,
}

#[derive(Debug, Error)]
pub enum BulkUpdateEntitiesPropertyOptionsErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),
    #[error("Cannot update more than {MAX_BULK_ENTITIES} entities at once")]
    TooManyEntities,
    #[error("Cannot change more than {MAX_OPTION_IDS_PER_PROPERTY} options at once")]
    TooManyOptions,
}

impl IntoResponse for BulkUpdateEntitiesPropertyOptionsErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            BulkUpdateEntitiesPropertyOptionsErr::Properties(e) => properties_err_status(e),
            BulkUpdateEntitiesPropertyOptionsErr::TooManyEntities
            | BulkUpdateEntitiesPropertyOptionsErr::TooManyOptions => StatusCode::BAD_REQUEST,
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "BulkUpdateEntitiesPropertyOptionsErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Reject oversized requests before any permission checks or database work, so
/// one authenticated call can't force unbounded receipt-minting and lock work.
fn validate_bulk_entities_option_request(
    request: &BulkUpdateEntitiesPropertyOptionsRequest,
) -> Result<(), BulkUpdateEntitiesPropertyOptionsErr> {
    if request.entities.len() > MAX_BULK_ENTITIES {
        return Err(BulkUpdateEntitiesPropertyOptionsErr::TooManyEntities);
    }
    if request.add_option_ids.len() + request.remove_option_ids.len() > MAX_OPTION_IDS_PER_PROPERTY
    {
        return Err(BulkUpdateEntitiesPropertyOptionsErr::TooManyOptions);
    }
    Ok(())
}

/// Apply one shared option delta (add / remove option ids on a single
/// multi-select property) to many entities in one request — e.g. tag a set of
/// emails with one label.
///
/// Best-effort per entity: one edit receipt is minted per entity, entities the
/// caller can't edit are reported as `skipped_no_permission` (mirroring the
/// read path, which silently drops entities the caller can't view), and each
/// permitted entity is updated in its own transaction so one entity failing
/// does not roll back the others. Returns one result per requested entity in
/// request order, with the reconciled final option ids for the successes.
#[utoipa::path(
    post,
    path = "/properties/options/bulk",
    request_body = BulkUpdateEntitiesPropertyOptionsRequest,
    responses(
        (status = 200, description = "Per-entity results: each entity applied, skipped, or failed", body = BulkUpdateEntitiesPropertyOptionsResponse),
        (status = 400, description = "Invalid request, the property is not multi-select, or an option does not belong to the property"),
        (status = 401, description = "Unauthenticated"),
        (status = 500, description = "Internal server error")
    ),
    tags = ["Properties"]
)]
#[tracing::instrument(skip(state, request, user), fields(entity_count = request.entities.len(), property_id = %request.property_id), err)]
pub async fn bulk_update_entities_property_options<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
    Json(request): Json<BulkUpdateEntitiesPropertyOptionsRequest>,
) -> Result<Json<BulkUpdateEntitiesPropertyOptionsResponse>, BulkUpdateEntitiesPropertyOptionsErr> {
    tracing::info!("bulk updating property options across entities");

    let user = user.authorization.user.macro_user_id;
    validate_bulk_entities_option_request(&request)?;

    let BulkUpdateEntitiesPropertyOptionsRequest {
        entities,
        property_id,
        add_option_ids,
        remove_option_ids,
    } = request;

    // Mint one edit receipt per entity. Entities the caller can't edit are
    // recorded as skipped and never handed to the service.
    let mut results: Vec<Option<BulkEntityOptionUpdateResult>> =
        (0..entities.len()).map(|_| None).collect();
    let mut receipts: Vec<EditReceipt> = Vec::new();
    let mut granted_indices: Vec<usize> = Vec::new();

    for (index, entity_ref) in entities.iter().enumerate() {
        match mint_authenticated_receipt::<EditAccessLevel, A>(
            state.entity_access_service.as_ref(),
            &user,
            &entity_ref.entity_id,
            target_entity_type(entity_ref.entity_type),
        )
        .await
        {
            Ok(receipt) => {
                receipts.push(receipt);
                granted_indices.push(index);
            }
            Err(error) => {
                tracing::debug!(
                    entity_id = %entity_ref.entity_id,
                    entity_type = ?entity_ref.entity_type,
                    error = ?error,
                    "user lacks edit permission, skipping entity"
                );
                results[index] = Some(BulkEntityOptionUpdateResult {
                    entity_type: entity_ref.entity_type,
                    entity_id: entity_ref.entity_id.clone(),
                    status: BulkEntityOptionUpdateStatus::SkippedNoPermission,
                    option_ids: None,
                    error: None,
                });
            }
        }
    }

    if !receipts.is_empty() {
        let outcomes = state
            .properties_service
            .bulk_update_entities_property_options(
                &receipts,
                property_id,
                add_option_ids,
                remove_option_ids,
            )
            .await?;

        for (index, outcome) in granted_indices.into_iter().zip(outcomes) {
            let entity_ref = &entities[index];
            results[index] = Some(match outcome {
                EntityOptionUpdateOutcome::Applied { option_ids } => BulkEntityOptionUpdateResult {
                    entity_type: entity_ref.entity_type,
                    entity_id: entity_ref.entity_id.clone(),
                    status: BulkEntityOptionUpdateStatus::Applied,
                    option_ids: Some(option_ids),
                    error: None,
                },
                EntityOptionUpdateOutcome::Failed { message } => BulkEntityOptionUpdateResult {
                    entity_type: entity_ref.entity_type,
                    entity_id: entity_ref.entity_id.clone(),
                    status: BulkEntityOptionUpdateStatus::Failed,
                    option_ids: None,
                    error: Some(message),
                },
            });
        }
    }

    let results = results
        .into_iter()
        .map(|result| result.expect("every entity yields a result"))
        .collect();

    Ok(Json(BulkUpdateEntitiesPropertyOptionsResponse { results }))
}

#[derive(Debug, Error)]
pub enum DeleteEntityPropertyErr {
    #[error(transparent)]
    Properties(#[from] PropertiesErr),
}

impl IntoResponse for DeleteEntityPropertyErr {
    fn into_response(self) -> Response {
        let status_code = match &self {
            DeleteEntityPropertyErr::Properties(e) => properties_err_status(e),
        };

        if status_code.is_server_error() {
            tracing::error!(
                error = ?self,
                error_type = "DeleteEntityPropertyErr",
                "Internal server error"
            );
        }

        (status_code, self.to_string()).into_response()
    }
}

/// Remove a specific entity property by its ID
#[utoipa::path(
    delete,
    path = "/properties/entity_properties/{entity_property_id}",
    params(
        ("entity_property_id" = Uuid, Path, description = "Entity Property ID")
    ),
    responses(
        (status = 204, description = "Entity property removed successfully"),
        (status = 403, description = "Property is required and cannot be removed, or no edit access"),
        (status = 404, description = "Entity property not found"),
        (status = 500, description = "Internal server error")
    ),
    tag = "Properties"
)]
#[tracing::instrument(skip(state, user), fields(entity_property_id = %entity_property_uuid), err)]
pub async fn delete_entity_property<
    S: PropertiesService,
    A: EntityAccessService,
    Auth: MacroAuthorizationService,
>(
    Path(entity_property_uuid): Path<Uuid>,
    State(state): State<PropertiesRouterState<S, A, Auth>>,
    user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
) -> Result<StatusCode, DeleteEntityPropertyErr> {
    let user = user.authorization.user.macro_user_id;
    tracing::info!("removing entity property");

    // The entity this property is attached to is only known after a lookup, so
    // the edit receipt is minted here instead of in an extractor.
    let property_info = state
        .properties_service
        .lookup_entity_property(entity_property_uuid)
        .await?
        .ok_or(PropertiesErr::EntityPropertyNotFound)?;

    let access = mint_authenticated_receipt::<EditAccessLevel, A>(
        state.entity_access_service.as_ref(),
        &user,
        &property_info.entity_id,
        property_info.entity_type,
    )
    .await?;

    state
        .properties_service
        .delete_entity_property(&access, entity_property_uuid)
        .await?;

    Ok(StatusCode::NO_CONTENT)
}