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

impl Database {
    pub async fn create_invite_link(&self, code: &str) -> Result<(), String> {
        let now = chrono::Utc::now().to_rfc3339();
        self.conn()
            .await?
            .execute(
                "INSERT INTO invite_links (code, created_at) VALUES (?1, ?2)",
                turso::params![code, now],
            )
            .await
            .map_err(|e| e.to_string())?;
        Ok(())
    }

    pub async fn get_all_invite_links(&self) -> Result<Vec<(String, String)>, String> {
        let mut rows = self
            .conn()
            .await?
            .query(
                "SELECT code, created_at FROM invite_links 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((
                row.get(0).map_err(|e| e.to_string())?,
                row.get(1).map_err(|e| e.to_string())?,
            ));
        }
        Ok(result)
    }

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

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

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