use crate::AppService;
use crate::error::AppError;
use serde::{Deserialize, Serialize};
use session::Session;
#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]
pub struct GitInitResponse {
    pub path: String,
    pub is_bare: bool,
}
#[derive(Debug, Clone, Deserialize, utoipa::ToSchema)]
pub struct GitInitRequest {
    pub path: String,
    #[serde(default)]
    pub bare: bool,
    #[serde(default)]
    pub initial_branch: Option<String>,
}
impl AppService {
    pub async fn git_init_bare(
        &self,
        request: GitInitRequest,
    ) -> Result<GitInitResponse, AppError> {
        let domain = git::GitDomain::init_bare(&request.path).map_err(AppError::from)?;
        Ok(GitInitResponse {
            path: domain.repo().path().to_string_lossy().to_string(),
            is_bare: true,
        })
    }

    pub async fn git_open(&self, path: String) -> Result<GitInitResponse, AppError> {
        let domain = git::GitDomain::open(&path).map_err(AppError::from)?;
        Ok(GitInitResponse {
            path: domain.repo().path().to_string_lossy().to_string(),
            is_bare: domain.repo().is_bare(),
        })
    }

    pub async fn git_open_workdir(&self, path: String) -> Result<GitInitResponse, AppError> {
        let domain = git::GitDomain::open_workdir(&path).map_err(AppError::from)?;
        Ok(GitInitResponse {
            path: domain.repo().path().to_string_lossy().to_string(),
            is_bare: true,
        })
    }

    pub async fn git_is_repo(&self, path: String) -> Result<bool, AppError> {
        match git::GitDomain::open(&path) {
            Ok(_) => Ok(true),
            Err(git::GitError::NotFound(_)) => Ok(false),
            Err(git::GitError::IoError(_)) => Ok(false),
            // Other errors (permission denied, corruption, etc.) indicate an abnormal
            // state that the caller should be aware of.
            Err(e) => Err(AppError::from(e)),
        }
    }

    pub async fn git_repo_path(
        &self,
        namespace: String,
        repo_name: String,
        ctx: &Session,
    ) -> Result<String, AppError> {
        let repo = self.utils_find_repo(namespace, repo_name, ctx).await?;
        Ok(repo.storage_path)
    }
}
