use serde_json::json;
use crate::error::{ApiError, Result};
use crate::models::{AuditAction, Collection, CreateCollectionRequest, UpdateCollectionRequest};
use crate::service::Services;
pub struct CollectionService;
impl CollectionService {
pub async fn create(
services: &Services,
request: CreateCollectionRequest,
user_id: &str,
) -> Result<Collection> {
if request.name.trim().is_empty() {
return Err(ApiError::Validation("Name cannot be empty".to_string()));
}
let collection = services.collections().create(request.clone(), user_id).await?;
services.audit().create(
"collection",
&collection.id,
AuditAction::Create,
json!({ "name": collection.name }),
user_id,
)
.await?;
Ok(collection)
}
pub async fn get(services: &Services, id: &str) -> Result<Collection> {
services.collections().get_by_id(id).await
}
pub async fn update(
services: &Services,
id: &str,
request: UpdateCollectionRequest,
user_id: &str,
) -> Result<Collection> {
if let Some(ref name) = request.name {
if name.trim().is_empty() {
return Err(ApiError::Validation("Name cannot be empty".to_string()));
}
}
let old_collection = services.collections().get_by_id(id).await?;
let collection = services.collections().update(id, request.clone(), user_id).await?;
services.audit().create(
"collection",
id,
AuditAction::Update,
json!({
"old": {
"name": old_collection.name,
"description": old_collection.description,
},
"new": {
"name": request.name,
"description": request.description,
}
}),
user_id,
)
.await?;
Ok(collection)
}
pub async fn delete(services: &Services, id: &str, user_id: &str) -> Result<()> {
services.collections().get_by_id(id).await?;
services.collections().delete(id).await?;
services.audit().create(
"collection",
id,
AuditAction::Delete,
json!({}),
user_id,
)
.await?;
Ok(())
}
pub async fn list(
services: &Services,
limit: i64,
cursor: Option<&str>,
) -> Result<(Vec<Collection>, Option<String>)> {
services.collections().list(limit, cursor).await
}
pub async fn add_asset(
services: &Services,
collection_id: &str,
asset_id: &str,
user_id: &str,
) -> Result<()> {
services.assets().get_by_id(asset_id).await?;
services.collections().add_asset(collection_id, asset_id).await?;
services.audit().create(
"collection",
collection_id,
AuditAction::AddToCollection,
json!({ "asset_id": asset_id }),
user_id,
)
.await?;
Ok(())
}
pub async fn remove_asset(
services: &Services,
collection_id: &str,
asset_id: &str,
user_id: &str,
) -> Result<()> {
services.collections().remove_asset(collection_id, asset_id).await?;
services.audit().create(
"collection",
collection_id,
AuditAction::RemoveFromCollection,
json!({ "asset_id": asset_id }),
user_id,
)
.await?;
Ok(())
}
}