// file: kb_lib/src/db/queries/pair_candle.rs

//! Queries for `k_sol_pair_candles`.

/// Inserts or updates one pair-candle row and returns its stable internal id.
pub async fn query_pair_candles_upsert(
    database: &crate::Database,
    dto: &crate::PairCandleDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_pair_candles (
    pair_id,
    timeframe_seconds,
    bucket_start_unix,
    bucket_end_unix,
    open_price_quote_per_base,
    high_price_quote_per_base,
    low_price_quote_per_base,
    close_price_quote_per_base,
    trade_count,
    buy_count,
    sell_count,
    base_volume_raw,
    quote_volume_raw,
    first_trade_signature,
    last_trade_signature,
    created_at,
    updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(pair_id, timeframe_seconds, bucket_start_unix) DO UPDATE SET
    bucket_end_unix = excluded.bucket_end_unix,
    open_price_quote_per_base = excluded.open_price_quote_per_base,
    high_price_quote_per_base = excluded.high_price_quote_per_base,
    low_price_quote_per_base = excluded.low_price_quote_per_base,
    close_price_quote_per_base = excluded.close_price_quote_per_base,
    trade_count = excluded.trade_count,
    buy_count = excluded.buy_count,
    sell_count = excluded.sell_count,
    base_volume_raw = excluded.base_volume_raw,
    quote_volume_raw = excluded.quote_volume_raw,
    first_trade_signature = excluded.first_trade_signature,
    last_trade_signature = excluded.last_trade_signature,
    updated_at = excluded.updated_at
                "#,
            )
            .bind(dto.pair_id)
            .bind(dto.timeframe_seconds)
            .bind(dto.bucket_start_unix)
            .bind(dto.bucket_end_unix)
            .bind(dto.open_price_quote_per_base)
            .bind(dto.high_price_quote_per_base)
            .bind(dto.low_price_quote_per_base)
            .bind(dto.close_price_quote_per_base)
            .bind(dto.trade_count)
            .bind(dto.buy_count)
            .bind(dto.sell_count)
            .bind(dto.base_volume_raw.clone())
            .bind(dto.quote_volume_raw.clone())
            .bind(dto.first_trade_signature.clone())
            .bind(dto.last_trade_signature.clone())
            .bind(dto.created_at.to_rfc3339())
            .bind(dto.updated_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = query_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_pair_candles on sqlite: {}",
                    error
                )));
            }

            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_pair_candles
WHERE pair_id = ? AND timeframe_seconds = ? AND bucket_start_unix = ?
LIMIT 1
                "#,
            )
            .bind(dto.pair_id)
            .bind(dto.timeframe_seconds)
            .bind(dto.bucket_start_unix)
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_pair_candles id for pair_id '{}' timeframe '{}' bucket '{}' on sqlite: {}",
                        dto.pair_id, dto.timeframe_seconds, dto.bucket_start_unix, error
                    )));
                },
            }
        },
    }
}

/// Returns one pair-candle row identified by `(pair_id, timeframe_seconds, bucket_start_unix)`.
pub async fn query_pair_candles_get_by_key(
    database: &crate::Database,
    pair_id: i64,
    timeframe_seconds: i64,
    bucket_start_unix: i64,
) -> Result<std::option::Option<crate::PairCandleDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::PairCandleEntity>(
                r#"
SELECT
    id,
    pair_id,
    timeframe_seconds,
    bucket_start_unix,
    bucket_end_unix,
    open_price_quote_per_base,
    high_price_quote_per_base,
    low_price_quote_per_base,
    close_price_quote_per_base,
    trade_count,
    buy_count,
    sell_count,
    base_volume_raw,
    quote_volume_raw,
    first_trade_signature,
    last_trade_signature,
    created_at,
    updated_at
FROM k_sol_pair_candles
WHERE pair_id = ? AND timeframe_seconds = ? AND bucket_start_unix = ?
LIMIT 1
                    "#,
            )
            .bind(pair_id)
            .bind(timeframe_seconds)
            .bind(bucket_start_unix)
            .fetch_optional(pool)
            .await;
            let entity_option = match query_result {
                Ok(entity_option) => entity_option,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot read k_sol_pair_candles by key on sqlite: {}",
                        error
                    )));
                },
            };
            match entity_option {
                Some(entity) => return crate::PairCandleDto::try_from(entity).map(Some),
                None => return Ok(None),
            }
        },
    }
}

/// Lists candles for one pair and one timeframe ordered by bucket start.
pub async fn query_pair_candles_list_by_pair_and_timeframe(
    database: &crate::Database,
    pair_id: i64,
    timeframe_seconds: i64,
) -> Result<std::vec::Vec<crate::PairCandleDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::PairCandleEntity>(
                r#"
SELECT
    id,
    pair_id,
    timeframe_seconds,
    bucket_start_unix,
    bucket_end_unix,
    open_price_quote_per_base,
    high_price_quote_per_base,
    low_price_quote_per_base,
    close_price_quote_per_base,
    trade_count,
    buy_count,
    sell_count,
    base_volume_raw,
    quote_volume_raw,
    first_trade_signature,
    last_trade_signature,
    created_at,
    updated_at
FROM k_sol_pair_candles
WHERE pair_id = ? AND timeframe_seconds = ?
ORDER BY bucket_start_unix ASC, id ASC
                    "#,
            )
            .bind(pair_id)
            .bind(timeframe_seconds)
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_pair_candles by pair_id '{}' timeframe '{}' on sqlite: {}",
                        pair_id, timeframe_seconds, error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::PairCandleDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}
