use db::sqlx;
use serde::{Deserialize, Serialize};
use session::Session;
use utoipa::ToSchema;

use crate::{AppService, error::AppError};

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct LanguageStatDto {
    pub language: String,
    pub bytes: i64,
    pub percentage: f32,
}

impl AppService {
    pub async fn git_repo_languages(
        &self,
        ctx: &Session,
        wk_name: &str,
        repo_name: &str,
    ) -> Result<Vec<LanguageStatDto>, AppError> {
        let repo = self.git_require_member(ctx, wk_name, repo_name).await?;

        let rows = sqlx::query_as::<_, (String, i64, f32)>(
            "SELECT language, bytes, percentage FROM repo_language WHERE repo = $1 \
             ORDER BY bytes DESC",
        )
        .bind(repo.id)
        .fetch_all(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;

        Ok(rows
            .into_iter()
            .map(|(language, bytes, percentage)| LanguageStatDto {
                language,
                bytes,
                percentage,
            })
            .collect())
    }
}
