//! Spike-item creation operations.

use std::path::Path;

use super::super::create_item_in_backlog;

/// Create a spike file and store it in the database.
///
/// Routes through `create_item_in_backlog`, the single internal creation path.
/// `acceptance_criteria` must be non-empty; an empty slice returns an error.
/// Returns the spike_id (e.g. `"4"`).
pub fn create_spike_file(
    root: &Path,
    name: &str,
    description: Option<&str>,
    acceptance_criteria: &[String],
    depends_on: Option<&[u32]>,
) -> Result<String, String> {
    let name_owned = name.to_string();
    let description_owned = description.map(str::to_string);
    let depends_on_owned: Option<Vec<u32>> = depends_on.map(<[u32]>::to_vec);
    let acs_owned: Vec<String> = acceptance_criteria.to_vec();

    create_item_in_backlog(
        root,
        "spike",
        name,
        acceptance_criteria,
        depends_on,
        move |spike_number| {
            let mut content = String::new();
            content.push_str("---\n");
            content.push_str("type: spike\n");
            content.push_str(&format!("name: \"{}\"\n", name_owned.replace('"', "\\\"")));
            if let Some(ref deps) = depends_on_owned.filter(|d| !d.is_empty()) {
                let nums: Vec<String> = deps.iter().map(|n| n.to_string()).collect();
                content.push_str(&format!("depends_on: [{}]\n", nums.join(", ")));
            }
            content.push_str("---\n\n");
            content.push_str(&format!("# Spike {spike_number}: {name_owned}\n\n"));
            content.push_str("## Question\n\n");
            if let Some(ref desc) = description_owned {
                content.push_str(desc);
                content.push('\n');
            } else {
                content.push_str("- TBD\n");
            }
            content.push('\n');
            content.push_str("## Hypothesis\n\n");
            content.push_str("- TBD\n\n");
            content.push_str("## Timebox\n\n");
            content.push_str("- TBD\n\n");
            content.push_str("## Investigation Plan\n\n");
            content.push_str("- TBD\n\n");
            content.push_str("## Findings\n\n");
            content.push_str("- TBD\n\n");
            content.push_str("## Recommendation\n\n");
            content.push_str("- TBD\n\n");
            content.push_str("## Acceptance Criteria\n\n");
            for criterion in &acs_owned {
                content.push_str(&format!("- [ ] {criterion}\n"));
            }
            content
        },
    )
}
