//! Epic work-item creation operations.
//!
//! Epics are shared-context containers that group related stories, bugs, spikes, and
//! refactors under a common goal. They are stored in the CRDT items list with
//! `type: epic` and are not pipeline-driven (no stage advancement).

use std::path::Path;

use super::super::create_item_in_backlog;

/// Create an epic file, storing it in the database via `create_item_in_backlog`.
///
/// Routes through `create_item_in_backlog` so that the tombstone-skip allocator
/// defence and post-write CRDT verification (added by bug 1001's fix) apply to
/// epics too.  Previously this function had its own ad-hoc allocate-and-write
/// path that bypassed those safety checks.
///
/// Returns the epic_id (numeric only, e.g. `"880"`).
pub fn create_epic_file(
    root: &Path,
    name: &str,
    goal: &str,
    motivation: Option<&str>,
    key_files: Option<&str>,
    success_criteria: Option<&[String]>,
) -> Result<String, String> {
    let name_owned = name.to_string();
    let goal_owned = goal.to_string();
    let motivation_owned = motivation.map(str::to_string);
    let key_files_owned = key_files.map(str::to_string);
    let success_criteria_owned: Vec<String> =
        success_criteria.map(|sc| sc.to_vec()).unwrap_or_default();

    // Epics don't have acceptance criteria; pass an empty slice.
    // create_item_in_backlog skips the AC check for type "epic".
    create_item_in_backlog(root, "epic", name, &[], None, move |epic_number| {
        let mut content = String::new();
        content.push_str("---\n");
        content.push_str("type: epic\n");
        content.push_str(&format!("name: \"{}\"\n", name_owned.replace('"', "\\\"")));
        content.push_str("---\n\n");
        content.push_str(&format!("# Epic {epic_number}: {name_owned}\n\n"));

        content.push_str("## Goal\n\n");
        content.push_str(&goal_owned);
        content.push_str("\n\n");

        content.push_str("## Motivation\n\n");
        if let Some(ref m) = motivation_owned {
            content.push_str(m);
            content.push('\n');
        } else {
            content.push_str("- TBD\n");
        }
        content.push('\n');

        content.push_str("## Key Files\n\n");
        if let Some(ref kf) = key_files_owned {
            content.push_str(kf);
            content.push('\n');
        } else {
            content.push_str("- TBD\n");
        }
        content.push('\n');

        content.push_str("## Success Criteria\n\n");
        if !success_criteria_owned.is_empty() {
            for c in &success_criteria_owned {
                content.push_str(&format!("- {c}\n"));
            }
        } else {
            content.push_str("- TBD\n");
        }

        content
    })
}
