use sqlx::MySqlPool;
use crate::device::storage::sql_common::{SqlDeviceStoreError, SweepCutoffs};
use crate::device::store::SweepCounts;
pub(super) async fn run(
pool: &MySqlPool,
tenant: &str,
cutoffs: &SweepCutoffs,
) -> Result<SweepCounts, SqlDeviceStoreError> {
let trusted_demoted = sqlx::query(
"UPDATE devices SET trust_level = 'Seen', demoted_at = ? \
WHERE tenant_id = ? \
AND trust_level = 'Trusted' \
AND last_seen_at < ?",
)
.bind(cutoffs.now)
.bind(tenant)
.bind(cutoffs.trusted)
.execute(pool)
.await?
.rows_affected();
let seen_demoted = sqlx::query(
"UPDATE devices SET trust_level = 'Revoked', revoked_at = ?, demoted_at = NULL \
WHERE tenant_id = ? \
AND trust_level = 'Seen' \
AND last_seen_at < ? \
AND (demoted_at IS NULL OR demoted_at < ?)",
)
.bind(cutoffs.now)
.bind(tenant)
.bind(cutoffs.seen)
.bind(cutoffs.seen)
.execute(pool)
.await?
.rows_affected();
let purged = sqlx::query(
"DELETE FROM devices \
WHERE tenant_id = ? \
AND trust_level = 'Revoked' \
AND revoked_at IS NOT NULL \
AND revoked_at < ?",
)
.bind(tenant)
.bind(cutoffs.grace)
.execute(pool)
.await?
.rows_affected();
Ok(SweepCounts {
trusted_to_seen: trusted_demoted,
seen_to_revoked: seen_demoted,
revoked_purged: purged,
})
}