use super::*;

pub(crate) fn validate_material_conflict_destination(
    world: &World,
    destination: &Path,
) -> Result<String, String> {
    let root = PathBuf::from(&world.resource::<crate::project_io::ProjectWorkspace>().root);
    let root = root.canonicalize().unwrap_or(root);
    let absolute = if destination.is_absolute() {
        destination.to_path_buf()
    } else {
        root.join(destination)
    };
    let absolute = absolute
        .parent()
        .and_then(|parent| parent.canonicalize().ok())
        .and_then(|parent| destination.file_name().map(|name| parent.join(name)))
        .unwrap_or(absolute);
    let relative = absolute.strip_prefix(&root).map_err(|_| {
        format!(
            "Material assets must stay inside {}",
            root.join("assets").display()
        )
    })?;
    if !relative.starts_with("assets") {
        return Err(format!(
            "Material assets must stay inside {}",
            root.join("assets").display()
        ));
    }
    Ok(relative.to_string_lossy().replace('\\', "/"))
}
