//! `voice_unset` — turn voice mode OFF (keeps row, just flips bit).

use serde::Deserialize;
use serde_json::{json, Value};

use super::VoiceToolContext;
use crate::audit::TOPIC_TOGGLE_CHANGED;
use crate::error::{Result, VoiceError};
use crate::policy::PolicyDimension;

#[derive(Debug, Deserialize)]
struct Args {
    context: UnsetContext,
}

#[derive(Debug, Deserialize)]
struct UnsetContext {
    conversation_key: String,
    #[serde(default = "default_source")]
    source: String,
}

fn default_source() -> String {
    "ui".to_string()
}

pub async fn handle(ctx: &VoiceToolContext, args: Value) -> Result<Value> {
    let parsed: Args = serde_json::from_value(args)
        .map_err(|e| VoiceError::InvalidParam(format!("voice_unset: {e}")))?;

    if parsed.context.source == "llm"
        && !ctx.policy.dimension_allowed(PolicyDimension::Toggle)
    {
        return Err(VoiceError::InvalidParam(
            "voice_unset: LLM toggle denied by policy.allow_toggle=false".into(),
        ));
    }

    let row = ctx
        .store
        .upsert(
            &parsed.context.conversation_key,
            false,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .await?;

    Ok(json!({
        "ok": true,
        "row": row,
        "audit_topic": TOPIC_TOGGLE_CHANGED,
        "source": parsed.context.source,
    }))
}
