use super::{PgPool, Uuid}; /// Toggle endorsement: insert if missing, delete if exists. Returns true if now endorsed. /// Uses a transaction to prevent race conditions between concurrent toggle requests. #[tracing::instrument(skip_all)] pub async fn toggle_endorsement( pool: &PgPool, post_id: Uuid, endorser_id: Uuid, ) -> Result { let mut tx = pool.begin().await?; let result = sqlx::query!( "INSERT INTO post_endorsements (post_id, endorser_id) VALUES ($1, $2) ON CONFLICT DO NOTHING", post_id, endorser_id, ) .execute(&mut *tx) .await?; if result.rows_affected() == 0 { // Already existed; remove it sqlx::query!( "DELETE FROM post_endorsements WHERE post_id = $1 AND endorser_id = $2", post_id, endorser_id, ) .execute(&mut *tx) .await?; tx.commit().await?; Ok(false) } else { tx.commit().await?; Ok(true) } }