use crate::db::pool;
use crate::models::ActivityLog;
use rusqlite::params;

#[tauri::command]
pub fn get_activity(project_id: String, limit: Option<i64>) -> Result<Vec<ActivityLog>, String> {
    let conn = pool().get().map_err(|e| e.to_string())?;
    let lim = limit.unwrap_or(20);
    let mut stmt = conn
        .prepare("SELECT * FROM activity_log WHERE project_id = ?1 ORDER BY created_at DESC LIMIT ?2")
        .map_err(|e| e.to_string())?;
    let result = stmt.query_map(params![project_id, lim], ActivityLog::from_row)
        .map_err(|e| e.to_string())?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| e.to_string());
    result
}

#[tauri::command]
pub fn add_activity(project_id: String, summary: String) -> Result<(), String> {
    let conn = pool().get().map_err(|e| e.to_string())?;
    let exists: bool = conn
        .query_row("SELECT 1 FROM project_workspaces WHERE id = ?1", params![project_id], |_| Ok(true))
        .unwrap_or(false);
    if !exists {
        return Err(format!("Project not found: {project_id}"));
    }
    conn.execute(
        "INSERT INTO activity_log (project_id, summary, created_at) VALUES (?1, ?2, datetime('now'))",
        params![project_id, summary],
    )
    .map_err(|e| e.to_string())?;
    conn.execute(
        "UPDATE project_workspaces SET updated_at = datetime('now') WHERE id = ?1",
        params![project_id],
    )
    .map_err(|e| e.to_string())?;
    Ok(())
}
