use camino::Utf8PathBuf;
use iri_string::types::UriAbsoluteString;

use crate::event_loop::ExtensionState;

#[tracing::instrument(skip(extension_state))]
pub async fn handle(
    old_uri: UriAbsoluteString,
    new_uri: UriAbsoluteString,
    extension_state: &mut ExtensionState,
) {
    let Some((repository_path, old_path, repository)) =
        extension_state.get_repository_mut(&old_uri)
    else {
        tracing::info!(message = "Ignoring filesystem changes");
        return;
    };

    if new_uri.scheme_str() != "file" {
        tracing::info!(message = "Ignoring move to unsupported URI");
        return;
    }

    // TODO: handle moving between repositories, and in/out of them
    let new_path = Utf8PathBuf::from(new_uri.path_str())
        .strip_prefix(repository_path)
        .unwrap()
        .to_path_buf();

    match repository.repository.move_path(old_path, new_path) {
        Ok(()) => {
            tracing::info!(message = "Moved paths");
        }
        Err(error) => {
            tracing::error!(message = "Failed to move paths", ?error);
        }
    }
}