use crate::AppService;
use crate::error::AppError;
use models::projects::{project, project_members};
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
use serde::{Deserialize, Serialize};
use session::Session;
use utoipa::ToSchema;
use uuid::Uuid;

#[derive(Deserialize, Serialize, Debug, ToSchema)]
pub struct CanUseProjectItem {
    pub name: String,
    pub avatar_url: Option<String>,
    pub display_name: String,
    pub uid: Uuid,
    pub is_public: bool,
}
impl AppService {
    pub async fn can_use_project(&self, ctx: &Session) -> Result<Vec<CanUseProjectItem>, AppError> {
        let user_uid = ctx.user().ok_or(AppError::Unauthorized)?;
        let member = project_members::Entity::find()
            .filter(project_members::Column::User.eq(user_uid))
            .all(&self.db)
            .await?;
        let mut result = vec![];
        for member in member {
            if let Some(project) = project::Entity::find_by_id(member.project)
                .one(&self.db)
                .await?
            {
                result.push(CanUseProjectItem {
                    name: project.name,
                    avatar_url: project.avatar_url,
                    display_name: project.display_name,
                    uid: project.id,
                    is_public: project.is_public,
                });
            }
        }
        Ok(result)
    }
}
