Skip to content
use crate::db::Database;

impl Database {
    pub async fn add_favorite_exercise(
        &self,
        user_id: &str,
        exercise_id: &str,
    ) -> Result<(), String> {
        self.conn()
            .await?
            .execute(
                "INSERT OR IGNORE INTO favorite_exercises (user_id, exercise_id) VALUES (?1, ?2)",
                turso::params![user_id, exercise_id],
            )
            .await
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub async fn remove_favorite_exercise(
        &self,
        user_id: &str,
        exercise_id: &str,
    ) -> Result<(), String> {
        self.conn()
            .await?
            .execute(
                "DELETE FROM favorite_exercises WHERE user_id = ?1 AND exercise_id = ?2",
                turso::params![user_id, exercise_id],
            )
            .await
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub async fn is_favorite_exercise(
        &self,
        user_id: &str,
        exercise_id: &str,
    ) -> Result<bool, String> {
        let mut rows = self
            .conn()
            .await?
            .query(
                "SELECT 1 FROM favorite_exercises WHERE user_id = ?1 AND exercise_id = ?2 LIMIT 1",
                turso::params![user_id, exercise_id],
            )
            .await
            .map_err(|e| e.to_string())?;

        Ok(rows.next().await.map_err(|e| e.to_string())?.is_some())
    }

    pub async fn get_favorite_exercise_ids(&self, user_id: &str) -> Result<Vec<String>, String> {
        let mut rows = self
            .conn()
            .await?
            .query(
                "SELECT exercise_id FROM favorite_exercises WHERE user_id = ?1",
                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(row.get(0).map_err(|e| e.to_string())?);
        }
        Ok(result)
    }
}