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

//! Queries for `k_sol_dex_decoded_events`.

/// Inserts or updates one decoded DEX event row.
pub async fn query_dex_decoded_events_upsert(
    database: &crate::Database,
    dto: &crate::DexDecodedEventDto,
) -> Result<i64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
INSERT INTO k_sol_dex_decoded_events (
    transaction_id,
    instruction_id,
    protocol_name,
    program_id,
    event_kind,
    pool_account,
    lp_mint,
    token_a_mint,
    token_b_mint,
    market_account,
    payload_json,
    created_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(transaction_id, instruction_id, event_kind) DO UPDATE SET
    protocol_name = excluded.protocol_name,
    program_id = excluded.program_id,
    pool_account = excluded.pool_account,
    lp_mint = excluded.lp_mint,
    token_a_mint = excluded.token_a_mint,
    token_b_mint = excluded.token_b_mint,
    market_account = excluded.market_account,
    payload_json = excluded.payload_json
                "#,
            )
            .bind(dto.transaction_id)
            .bind(dto.instruction_id)
            .bind(dto.protocol_name.clone())
            .bind(dto.program_id.clone())
            .bind(dto.event_kind.clone())
            .bind(dto.pool_account.clone())
            .bind(dto.lp_mint.clone())
            .bind(dto.token_a_mint.clone())
            .bind(dto.token_b_mint.clone())
            .bind(dto.market_account.clone())
            .bind(dto.payload_json.clone())
            .bind(dto.created_at.to_rfc3339())
            .execute(pool)
            .await;
            if let Err(error) = query_result {
                return Err(crate::Error::Db(format!(
                    "cannot upsert k_sol_dex_decoded_events on sqlite: {}",
                    error
                )));
            }
            let id_result = sqlx::query_scalar::<sqlx::Sqlite, i64>(
                r#"
SELECT id
FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND (
        (instruction_id IS NULL AND ? IS NULL)
        OR instruction_id = ?
      )
  AND event_kind = ?
LIMIT 1
                "#,
            )
            .bind(dto.transaction_id)
            .bind(dto.instruction_id)
            .bind(dto.instruction_id)
            .bind(dto.event_kind.clone())
            .fetch_one(pool)
            .await;
            match id_result {
                Ok(id) => return Ok(id),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_dex_decoded_events id on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes one decoded DEX event row by its natural key.
pub async fn query_dex_decoded_events_delete_by_key(
    database: &crate::Database,
    transaction_id: i64,
    instruction_id: std::option::Option<i64>,
    event_kind: &str,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND (
        (instruction_id IS NULL AND ? IS NULL)
        OR instruction_id = ?
      )
  AND event_kind = ?
                "#,
            )
            .bind(transaction_id)
            .bind(instruction_id)
            .bind(instruction_id)
            .bind(event_kind)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete k_sol_dex_decoded_events by key on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Reads one decoded DEX event by its natural key.
pub async fn query_dex_decoded_events_get_by_key(
    database: &crate::Database,
    transaction_id: i64,
    instruction_id: std::option::Option<i64>,
    event_kind: &str,
) -> Result<std::option::Option<crate::DexDecodedEventDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::DexDecodedEventEntity>(
                r#"
SELECT
    id,
    transaction_id,
    instruction_id,
    protocol_name,
    program_id,
    event_kind,
    pool_account,
    lp_mint,
    token_a_mint,
    token_b_mint,
    market_account,
    payload_json,
    created_at
FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND (
        (instruction_id IS NULL AND ? IS NULL)
        OR instruction_id = ?
      )
  AND event_kind = ?
LIMIT 1
                "#,
            )
            .bind(transaction_id)
            .bind(instruction_id)
            .bind(instruction_id)
            .bind(event_kind.to_string())
            .fetch_optional(pool)
            .await;
            let entity_option = match query_result {
                Ok(entity_option) => entity_option,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot fetch k_sol_dex_decoded_events on sqlite: {}",
                        error
                    )));
                },
            };
            match entity_option {
                Some(entity) => {
                    let dto_result = crate::DexDecodedEventDto::try_from(entity);
                    match dto_result {
                        Ok(dto) => return Ok(Some(dto)),
                        Err(error) => return Err(error),
                    }
                },
                None => return Ok(None),
            }
        },
    }
}

/// Lists decoded DEX events for one transaction.
pub async fn query_dex_decoded_events_list_by_transaction_id(
    database: &crate::Database,
    transaction_id: i64,
) -> Result<std::vec::Vec<crate::DexDecodedEventDto>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query_as::<sqlx::Sqlite, crate::DexDecodedEventEntity>(
                r#"
SELECT
    id,
    transaction_id,
    instruction_id,
    protocol_name,
    program_id,
    event_kind,
    pool_account,
    lp_mint,
    token_a_mint,
    token_b_mint,
    market_account,
    payload_json,
    created_at
FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
ORDER BY id ASC
                "#,
            )
            .bind(transaction_id)
            .fetch_all(pool)
            .await;
            let entities = match query_result {
                Ok(entities) => entities,
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot list k_sol_dex_decoded_events on sqlite: {}",
                        error
                    )));
                },
            };
            let mut dtos = std::vec::Vec::new();
            for entity in entities {
                let dto_result = crate::DexDecodedEventDto::try_from(entity);
                let dto = match dto_result {
                    Ok(dto) => dto,
                    Err(error) => return Err(error),
                };
                dtos.push(dto);
            }
            return Ok(dtos);
        },
    }
}

/// Returns the latest Pump.fun create payload associated with a token mint.
pub async fn query_dex_decoded_events_get_latest_pump_fun_create_payload_by_mint(
    database: &crate::Database,
    mint: &str,
) -> Result<std::option::Option<std::string::String>, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let payload_result = sqlx::query_scalar::<sqlx::Sqlite, std::string::String>(
                r#"
SELECT payload_json
FROM k_sol_dex_decoded_events
WHERE protocol_name = 'pump_fun'
  AND event_kind IN ('pump_fun.create', 'pump_fun.create_v2_token')
  AND (
        token_a_mint = ?
     OR json_extract(payload_json, '$.mint') = ?
     OR json_extract(payload_json, '$.tokenMint') = ?
  )
ORDER BY id DESC
LIMIT 1
                "#,
            )
            .bind(mint)
            .bind(mint)
            .bind(mint)
            .fetch_optional(pool)
            .await;
            match payload_result {
                Ok(payload_option) => return Ok(payload_option),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot read latest pump.fun create payload for mint '{}' on sqlite: {}",
                        mint, error
                    )));
                },
            }
        },
    }
}

#[cfg(test)]
mod tests {
    async fn make_database() -> crate::Database {
        let tempdir_result = tempfile::tempdir();
        let tempdir = match tempdir_result {
            Ok(tempdir) => tempdir,
            Err(error) => panic!("tempdir must succeed: {}", error),
        };
        let database_path = tempdir.path().join("dex_decoded_event.sqlite3");
        let config = crate::DatabaseConfig {
            enabled: true,
            backend: crate::DatabaseBackend::Sqlite,
            sqlite: crate::SqliteDatabaseConfig {
                path: database_path.to_string_lossy().to_string(),
                create_if_missing: true,
                busy_timeout_ms: 5000,
                max_connections: 1,
                auto_initialize_schema: true,
                use_wal: true,
            },
        };
        let database_result = crate::Database::connect_and_initialize(&config).await;
        match database_result {
            Ok(database) => return database,
            Err(error) => panic!("database init must succeed: {}", error),
        }
    }

    #[tokio::test]
    async fn dex_decoded_event_roundtrip_works() {
        let database = make_database().await;
        let transaction_dto = crate::ChainTransactionDto::new(
            "sig-dex-event-test-1".to_string(),
            None,
            None,
            Some("helius_primary_http".to_string()),
            Some("0".to_string()),
            None,
            None,
            r#"{"transaction":{"message":{"instructions":[]}}}"#.to_string(),
        );
        let transaction_id_result =
            crate::query_chain_transactions_upsert(&database, &transaction_dto).await;
        let transaction_id = match transaction_id_result {
            Ok(transaction_id) => transaction_id,
            Err(error) => panic!("transaction upsert must succeed: {}", error),
        };
        let instruction_dto = crate::ChainInstructionDto::new(
            transaction_id,
            None,
            0,
            None,
            Some(crate::RAYDIUM_AMM_V4_PROGRAM_ID.to_string()),
            Some("raydium-amm-v4".to_string()),
            Some(1),
            r#"["Account0","Pool111","Lp111","TokenA111","TokenB111"]"#.to_string(),
            None,
            None,
            None,
        );
        let instruction_id_result =
            crate::query_chain_instructions_insert(&database, &instruction_dto).await;
        let instruction_id = match instruction_id_result {
            Ok(instruction_id) => instruction_id,
            Err(error) => panic!("instruction insert must succeed: {}", error),
        };
        let dto = crate::DexDecodedEventDto::new(
            transaction_id,
            Some(instruction_id),
            "raydium_amm_v4".to_string(),
            crate::RAYDIUM_AMM_V4_PROGRAM_ID.to_string(),
            "raydium_amm_v4.initialize2_pool".to_string(),
            Some("Pool111".to_string()),
            Some("Lp111".to_string()),
            Some("TokenA111".to_string()),
            Some("TokenB111".to_string()),
            Some("Market111".to_string()),
            r#"{"k":"v"}"#.to_string(),
        );
        let event_id_result = crate::query_dex_decoded_events_upsert(&database, &dto).await;
        let event_id = match event_id_result {
            Ok(event_id) => event_id,
            Err(error) => panic!("event upsert must succeed: {}", error),
        };
        assert!(event_id > 0);
        let fetched_result = crate::query_dex_decoded_events_get_by_key(
            &database,
            transaction_id,
            Some(instruction_id),
            "raydium_amm_v4.initialize2_pool",
        )
        .await;
        let fetched_option = match fetched_result {
            Ok(fetched_option) => fetched_option,
            Err(error) => panic!("event fetch must succeed: {}", error),
        };
        let fetched = match fetched_option {
            Some(fetched) => fetched,
            None => panic!("event must exist"),
        };
        assert_eq!(fetched.id, Some(event_id));
        assert_eq!(fetched.transaction_id, transaction_id);
        assert_eq!(fetched.instruction_id, Some(instruction_id));
        assert_eq!(fetched.protocol_name, "raydium_amm_v4");
        assert_eq!(fetched.pool_account, Some("Pool111".to_string()));
        let listed_result =
            crate::query_dex_decoded_events_list_by_transaction_id(&database, transaction_id).await;
        let listed = match listed_result {
            Ok(listed) => listed,
            Err(error) => panic!("event list must succeed: {}", error),
        };
        assert_eq!(listed.len(), 1);
        assert_eq!(listed[0].event_kind, "raydium_amm_v4.initialize2_pool");
    }
}
