use crate::error::AppError;
use crate::models::agent::{Agent, AgentRole, AgentTool};
use crate::AppState;
use rusqlite::params;
use tauri::State;

#[tauri::command]
pub fn create_agent(
    state: State<'_, AppState>,
    name: String,
    role: AgentRole,
    tool: AgentTool,
    custom_prompt: String,
) -> Result<Agent, AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let agent = Agent::insert(&db, &name, role, tool, &custom_prompt)?;
    Ok(agent)
}

#[tauri::command]
pub fn list_agents(state: State<'_, AppState>) -> Result<Vec<Agent>, AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let agents = Agent::list(&db)?;
    Ok(agents)
}

#[tauri::command]
pub fn get_agent(state: State<'_, AppState>, id: String) -> Result<Agent, AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let agent = Agent::get_by_id(&db, &id)?;
    Ok(agent)
}

#[tauri::command]
pub fn update_agent(
    state: State<'_, AppState>,
    id: String,
    name: String,
    role: AgentRole,
    tool: AgentTool,
    custom_prompt: String,
) -> Result<(), AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let previous = Agent::get_by_id(&db, &id)?;
    Agent::update(&db, &id, &name, role.clone(), tool, &custom_prompt)?;

    if previous.role != role {
        match role {
            AgentRole::Analyst => {
                db.execute(
                    "UPDATE watched_trackers
                     SET developer_agent_id = NULL,
                         status = 'invalid'
                     WHERE developer_agent_id = ?1",
                    params![id],
                )?;
            }
            AgentRole::Developer => {
                db.execute(
                    "UPDATE watched_trackers
                     SET analyst_agent_id = NULL,
                         status = 'invalid'
                     WHERE analyst_agent_id = ?1",
                    params![id],
                )?;
            }
        }
    }

    Ok(())
}

#[tauri::command]
pub fn delete_agent(state: State<'_, AppState>, id: String) -> Result<(), AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    Agent::delete(&db, &id)?;
    Ok(())
}
