use crate::auth::ExerciseLog;
use crate::db::Database;
impl Database {
pub async fn create_exercise_log(&self, log: &ExerciseLog) -> Result<(), String> {
self.conn()
.await?
.execute(
"INSERT INTO exercise_logs (id, user_id, exercise_id, amount, points_earned, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
turso::params![log.id.clone(), log.user_id.clone(), log.exercise_id.clone(), log.amount, log.points_earned, log.created_at.clone()],
)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
pub async fn get_exercise_logs_for_user(
&self,
user_id: &str,
) -> Result<Vec<ExerciseLog>, String> {
let mut rows = self
.conn()
.await?
.query(
"SELECT id, user_id, exercise_id, amount, points_earned, created_at FROM exercise_logs WHERE user_id = ?1 ORDER BY created_at DESC",
turso::params![user_id],
)
.await
.map_err(|e| e.to_string())?;
let mut result = Vec::new();
while let Some(row) = rows.next().await.map_err(|e| e.to_string())? {
result.push(ExerciseLog {
id: row.get(0).map_err(|e| e.to_string())?,
user_id: row.get(1).map_err(|e| e.to_string())?,
exercise_id: row.get(2).map_err(|e| e.to_string())?,
amount: row.get(3).map_err(|e| e.to_string())?,
points_earned: row.get(4).map_err(|e| e.to_string())?,
created_at: row.get(5).map_err(|e| e.to_string())?,
});
}
Ok(result)
}
pub async fn get_all_exercise_logs(&self) -> Result<Vec<ExerciseLog>, String> {
let mut rows = self
.conn()
.await?
.query(
"SELECT id, user_id, exercise_id, amount, points_earned, created_at FROM exercise_logs ORDER BY created_at DESC",
(),
)
.await
.map_err(|e| e.to_string())?;
let mut result = Vec::new();
while let Some(row) = rows.next().await.map_err(|e| e.to_string())? {
result.push(ExerciseLog {
id: row.get(0).map_err(|e| e.to_string())?,
user_id: row.get(1).map_err(|e| e.to_string())?,
exercise_id: row.get(2).map_err(|e| e.to_string())?,
amount: row.get(3).map_err(|e| e.to_string())?,
points_earned: row.get(4).map_err(|e| e.to_string())?,
created_at: row.get(5).map_err(|e| e.to_string())?,
});
}
Ok(result)
}
pub async fn get_points_for_user(&self, user_id: &str) -> Result<f64, String> {
let mut rows = self
.conn()
.await?
.query(
"SELECT COALESCE(SUM(points_earned), 0.0) FROM exercise_logs WHERE user_id = ?1",
turso::params![user_id],
)
.await
.map_err(|e| e.to_string())?;
if let Some(row) = rows.next().await.map_err(|e| e.to_string())? {
Ok(row.get(0).map_err(|e| e.to_string())?)
} else {
Ok(0.0)
}
}
pub async fn delete_exercise_log(&self, id: &str) -> Result<(), String> {
self.conn()
.await?
.execute(
"DELETE FROM exercise_logs WHERE id = ?1",
turso::params![id],
)
.await
.map_err(|e| e.to_string())?;
Ok(())
}
}