use common_contracts::dtos::SessionDataDto;
use sqlx::PgPool;
use uuid::Uuid;

pub async fn insert_session_data(
    pool: &PgPool,
    dto: &SessionDataDto,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        r#"
        INSERT INTO session_raw_data (request_id, symbol, provider, data_type, data_payload)
        VALUES ($1, $2, $3, $4, $5)
        "#,
    )
    .bind(dto.request_id)
    .bind(&dto.symbol)
    .bind(&dto.provider)
    .bind(&dto.data_type)
    .bind(&dto.data_payload)
    .execute(pool)
    .await?;

    Ok(())
}

pub async fn get_session_data(
    pool: &PgPool,
    request_id: Uuid,
) -> Result<Vec<SessionDataDto>, sqlx::Error> {
    let records = sqlx::query_as!(
        SessionDataDto,
        r#"
        SELECT 
            request_id, 
            symbol, 
            provider, 
            data_type, 
            data_payload, 
            created_at
        FROM session_raw_data
        WHERE request_id = $1
        ORDER BY created_at ASC
        "#,
        request_id
    )
    .fetch_all(pool)
    .await?;

    Ok(records)
}

pub async fn delete_session_data(
    pool: &PgPool,
    request_id: Uuid,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        r#"
        DELETE FROM session_raw_data
        WHERE request_id = $1
        "#,
    )
    .bind(request_id)
    .execute(pool)
    .await?;

    Ok(())
}

pub async fn clear_all_session_data(
    pool: &PgPool,
) -> Result<(), sqlx::Error> {
    sqlx::query("TRUNCATE TABLE session_raw_data")
        .execute(pool)
        .await?;
    Ok(())
}

