use crate::AppService;
use crate::error::AppError;
use models::projects::{Project, ProjectHistoryName, project_history_name};
use sea_orm::*;
use session::Session;

impl AppService {
    pub async fn project_standard_name(
        &self,
        name: String,
        ctx: &Session,
    ) -> Result<String, AppError> {
        let project = Project::find()
            .filter(
                Condition::any()
                    .add(<Project as EntityTrait>::Column::Name.ilike(&name))
                    .add(<Project as EntityTrait>::Column::Name.eq(&name)),
            )
            .one(&self.db)
            .await?;

        if let Some(project) = project {
            if !project.is_public {
                if let Err(_) = self
                    .utils_project_context_role(&ctx, project.name.clone())
                    .await
                {
                    return Err(AppError::PermissionDenied);
                }
            }
            return Ok(project.name);
        }

        let project_history = ProjectHistoryName::find()
            .filter(
                Condition::any()
                    .add(project_history_name::Column::HistoryName.ilike(&name))
                    .add(project_history_name::Column::HistoryName.eq(&name)),
            )
            .one(&self.db)
            .await?;

        if let Some(project_history) = project_history {
            if let Some(project) = Project::find_by_id(project_history.project_uid)
                .one(&self.db)
                .await?
            {
                if !project.is_public {
                    if let Err(_) = self
                        .utils_project_context_role(&ctx, project.name.clone())
                        .await
                    {
                        return Err(AppError::PermissionDenied);
                    }
                }
                return Ok(project.name);
            }
        }
        Err(AppError::ProjectNotFound)
    }
}
