use serde::{Deserialize, Serialize};

use crate::{
    bare::GitBare,
    cmd::{
        tag::{tag_delete::TagDeleteParams, tag_init::TagInitParams},
        tagger::GitTagger,
    },
    errors::GitResult,
};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TagRenameParams {
    pub old_name: String,
    pub new_name: String,
    pub force: bool,
}

impl GitBare {
    pub fn tag_rename(&self, params: TagRenameParams) -> GitResult<()> {
        let old_info = self.tag_info(params.old_name.clone())?;
        let init_params = TagInitParams {
            name: params.new_name.clone(),
            target: old_info.target.clone(),
            message: old_info.message.clone(),
            tagger: if old_info.is_annotated {
                Some(GitTagger {
                    name: old_info.tagger.clone().unwrap_or_default(),
                    email: old_info.tagger_email.clone().unwrap_or_default(),
                })
            } else {
                None
            },
            force: params.force,
        };

        self.tag_init(init_params)?;
        self.tag_delete(TagDeleteParams {
            name: params.old_name.clone(),
        })?;

        Ok(())
    }
}
