use serde::{Deserialize, Serialize};

use crate::{
    bare::GitBare,
    cmd::{command::GitCommandParams, oid::ObjectId},
    errors::{GitError, GitResult},
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlobUploadParams {
    pub blob: Vec<u8>,
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlobUploadResult {
    pub id: ObjectId,
}

impl GitBare {
    pub fn blob_upload(
        &self,
        params: BlobUploadParams,
    ) -> GitResult<BlobUploadResult> {
        let cmd_params = GitCommandParams::new(vec![
            "hash-object".to_string(),
            "-w".to_string(),
            "--stdin".to_string(),
        ])
        .with_stdin(params.blob);

        let output = self.git_command_with(cmd_params)?;

        if !output.success {
            return Err(GitError::CommandFailed {
                status_code: output.status_code,
                stderr: output.stderr_lossy(),
            });
        }

        let stdout = output.stdout_lossy();
        let oid_str = stdout.trim();
        let oid = ObjectId::new(oid_str);

        Ok(BlobUploadResult { id: oid })
    }
}
