use crate::models::WorkflowHistory;
use common_contracts::dtos::NewWorkflowHistory;
use sqlx::PgPool;
use uuid::Uuid;

pub async fn create_workflow_history(
    pool: &PgPool,
    payload: &NewWorkflowHistory,
) -> Result<WorkflowHistory, sqlx::Error> {
    sqlx::query_as::<_, WorkflowHistory>(
        r#"
        INSERT INTO workflow_history (request_id, symbol, market, template_id, status, start_time, end_time, snapshot_data)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
        RETURNING request_id, symbol, market, template_id, status, start_time, end_time, snapshot_data, created_at
        "#
    )
    .bind(&payload.request_id)
    .bind(&payload.symbol)
    .bind(&payload.market)
    .bind(&payload.template_id)
    .bind(&payload.status)
    .bind(&payload.start_time)
    .bind(&payload.end_time)
    .bind(&payload.snapshot_data)
    .fetch_one(pool)
    .await
}

pub async fn get_workflow_history_by_id(
    pool: &PgPool,
    request_id: Uuid,
) -> Result<Option<WorkflowHistory>, sqlx::Error> {
    sqlx::query_as::<_, WorkflowHistory>(
        r#"
        SELECT request_id, symbol, market, template_id, status, start_time, end_time, snapshot_data, created_at
        FROM workflow_history
        WHERE request_id = $1
        "#
    )
    .bind(request_id)
    .fetch_optional(pool)
    .await
}

pub async fn get_workflow_histories(
    pool: &PgPool,
    symbol: Option<&str>,
    limit: i64,
) -> Result<Vec<WorkflowHistory>, sqlx::Error> {
    match symbol {
        Some(s) => {
             sqlx::query_as::<_, WorkflowHistory>(
                r#"
                SELECT request_id, symbol, market, template_id, status, start_time, end_time, snapshot_data, created_at
                FROM workflow_history
                WHERE symbol = $1
                ORDER BY created_at DESC
                LIMIT $2
                "#
            )
            .bind(s)
            .bind(limit)
            .fetch_all(pool)
            .await
        },
        None => {
            sqlx::query_as::<_, WorkflowHistory>(
                r#"
                SELECT request_id, symbol, market, template_id, status, start_time, end_time, snapshot_data, created_at
                FROM workflow_history
                ORDER BY created_at DESC
                LIMIT $1
                "#
            )
            .bind(limit)
            .fetch_all(pool)
            .await
        }
    }
}

