use std::fs;
use std::path::PathBuf;

use rho_core::{RhoResult, ensure_parent, normalize_actor_id, require_arg, uuid_like, yaml_quote};

fn usage() -> ! {
    eprintln!(
        "usage: rho message send --shared-root <path> --from <id> --to <id> --type <type> --text <text> [--related-request-id <id>] [--id <id>]"
    );
    std::process::exit(2);
}

pub fn run(args: &[String]) -> RhoResult<()> {
    if args.first().map(String::as_str) != Some("send") {
        usage();
    }
    let rest = &args[1..];
    let shared_root = PathBuf::from(require_arg(rest, "--shared-root").unwrap_or_else(|_| usage()));
    let from = normalize_actor_id(&require_arg(rest, "--from").unwrap_or_else(|_| usage()))?;
    let to = normalize_actor_id(&require_arg(rest, "--to").unwrap_or_else(|_| usage()))?;
    let message_type = require_arg(rest, "--type").unwrap_or_else(|_| usage());
    let text = require_arg(rest, "--text").unwrap_or_else(|_| usage());
    let id = rho_core::arg_value(rest, "--id").unwrap_or_else(|| format!("msg-{}", uuid_like()));
    let related = rho_core::arg_value(rest, "--related-request-id");
    let path = shared_root
        .join(".rho/inbox")
        .join(&to)
        .join(format!("{id}.yaml"));

    ensure_parent(&path)?;
    let related_line = related
        .as_ref()
        .map(|value| format!("  related_request_id: {}\n", yaml_quote(value)))
        .unwrap_or_default();
    fs::write(
        &path,
        format!(
            "version: 1\n\
message:\n\
  id: {}\n\
  from: {}\n\
  to: {}\n\
  type: {}\n\
{}\
  created_at: {}\n\
  body:\n\
    text: {}\n",
            yaml_quote(&id),
            yaml_quote(&from),
            yaml_quote(&to),
            yaml_quote(&message_type),
            related_line,
            yaml_quote(&rho_core::now_rfc3339()),
            yaml_quote(&text),
        ),
    )?;
    println!("{}", path.display());
    Ok(())
}
