use db::sqlx;
use model::issues::IssueEventModel;
use session::Session;

use super::types::{IssueEventResponse, issue_author};
use crate::{AppService, error::AppError, session_user};

impl AppService {
    pub async fn issue_events(
        &self,
        ctx: &Session,
        wk_name: &str,
        number: i64,
    ) -> Result<Vec<IssueEventResponse>, AppError> {
        let user_uid = session_user(ctx)?;
        let wk = self.workspace_resolve(wk_name).await?;
        self.workspace_require_member(wk.id, user_uid).await?;
        let issue = self.issue_resolve(wk.id, number).await?;

        let events = sqlx::query_as::<_, IssueEventModel>(
            "SELECT id, issue, actor, event, from_value, to_value, metadata, created_at \
             FROM issue_event WHERE issue = $1 \
             ORDER BY created_at ASC",
        )
        .bind(issue.id)
        .fetch_all(self.db.reader())
        .await
        .map_err(|e| AppError::DatabaseError(e.to_string()))?;

        let mut results = Vec::new();
        for event in events {
            let actor = if let Some(actor_uid) = event.actor {
                let user = self.users_find_by_id(actor_uid).await.ok();
                user.map(issue_author)
            } else {
                None
            };
            results.push(IssueEventResponse {
                actor,
                event: event.event,
                from_value: event.from_value,
                to_value: event.to_value,
                created_at: event.created_at,
            });
        }
        Ok(results)
    }
}
