use toml_edit::{Entry, Formatted, Item, Value};

use super::{Error, Manifest};

impl Manifest {
    /// Rewrite manifest by applying version normalization
    ///
    /// This drops any `"+meta"` suffix present in the SemVer string.
    pub fn normalize_version(&mut self) -> Result<(), Error> {
        let Some(package_item) = self.toml.get_mut("package") else {
            return Err(Error::manifest("Value at 'package' missing"));
        };

        let Some(package) = package_item.as_table_mut() else {
            return Err(Error::manifest("Value at 'package' is not a table"));
        };

        let Entry::Occupied(mut version_entry) = package.entry("version") else {
            return Err(Error::manifest("Value at 'package.version' missing"));
        };

        let Some(version) = version_entry.get().as_str() else {
            return Err(Error::manifest("Value at 'package.version' is not a string"));
        };

        if let Some((version_no_meta, _meta)) = version.split_once('+') {
            version_entry.insert(Item::Value(Value::String(Formatted::new(String::from(
                version_no_meta,
            )))));
        };

        Ok(())
    }
}
