use serde::{Deserialize, Serialize};

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

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlobLoadResult {
    pub params: BlobLoadParams,
    pub blob: Vec<u8>,
}

impl GitBare {
    pub fn blob_load(
        &self,
        params: &BlobLoadParams,
    ) -> GitResult<BlobLoadResult> {
        let repo = self.gix_repo()?;
        let gix_id: gix::hash::ObjectId = (&params.id).try_into()?;

        let blob = repo.find_blob(gix_id).map_err(|_| {
            GitError::ObjectNotFound(params.id.as_str().to_string())
        })?;

        Ok(BlobLoadResult {
            params: params.clone(),
            blob: blob.data.to_vec(),
        })
    }
}
