// 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 all locally decoded DEX rows and linked materialization for one transaction.
///
/// This reset is intentionally scoped by `protocol_name`, not by current coverage entries.
/// It removes legacy event kinds that no longer exist in the decoder, such as the old
/// `raydium_amm_v4.swap` row that was replaced by specialized AMM v4 swap variants.
pub async fn query_dex_decoded_events_delete_local_replay_scope_by_transaction_id(
    database: &crate::Database,
    transaction_id: i64,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let statements = [
                (
                    "k_sol_instruction_observations decoded links",
                    r#"
UPDATE k_sol_instruction_observations
SET decoded_event_id = NULL
WHERE decoded_event_id IN (
    SELECT id
    FROM k_sol_dex_decoded_events
    WHERE transaction_id = ?
      AND protocol_name IN (
          'raydium_amm_v4', 'raydium_cpmm', 'raydium_clmm', 'raydium_launchpad',
          'pump_fun', 'pump_fees', 'pump_swap', 'meteora_dbc', 'meteora_dlmm', 'meteora_damm_v1',
          'meteora_damm_v2', 'orca_whirlpools', 'fluxbeam', 'dexlab', 'openbook_v2',
          'phoenix_v1'
      )
)
                    "#,
                ),
                (
                    "k_sol_launch_attributions",
                    "DELETE FROM k_sol_launch_attributions WHERE transaction_id = ?",
                ),
                (
                    "k_sol_launch_events",
                    "DELETE FROM k_sol_launch_events WHERE transaction_id = ?",
                ),
                ("k_sol_trade_events", "DELETE FROM k_sol_trade_events WHERE transaction_id = ?"),
                (
                    "k_sol_liquidity_events",
                    "DELETE FROM k_sol_liquidity_events WHERE transaction_id = ?",
                ),
                (
                    "k_sol_pool_lifecycle_events",
                    "DELETE FROM k_sol_pool_lifecycle_events WHERE transaction_id = ?",
                ),
                (
                    "k_sol_fee_event_amounts",
                    "DELETE FROM k_sol_fee_event_amounts WHERE transaction_id = ?",
                ),
                ("k_sol_fee_events", "DELETE FROM k_sol_fee_events WHERE transaction_id = ?"),
                (
                    "k_sol_reward_events",
                    "DELETE FROM k_sol_reward_events WHERE transaction_id = ?",
                ),
                (
                    "k_sol_pool_admin_events",
                    "DELETE FROM k_sol_pool_admin_events WHERE transaction_id = ?",
                ),
                (
                    "k_sol_orderbook_events",
                    "DELETE FROM k_sol_orderbook_events WHERE transaction_id = ?",
                ),
                (
                    "k_sol_token_account_events",
                    "DELETE FROM k_sol_token_account_events WHERE transaction_id = ?",
                ),
                (
                    "k_sol_dex_decoded_events",
                    r#"
DELETE FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND protocol_name IN (
      'raydium_amm_v4', 'raydium_cpmm', 'raydium_clmm', 'raydium_launchpad',
      'pump_fun', 'pump_fees', 'pump_swap', 'meteora_dbc', 'meteora_dlmm', 'meteora_damm_v1',
      'meteora_damm_v2', 'orca_whirlpools', 'fluxbeam', 'dexlab', 'openbook_v2',
      'phoenix_v1'
  )
                    "#,
                ),
            ];
            let mut deleted_count = 0_u64;
            for (scope_name, statement) in statements {
                let query_result = sqlx::query(statement).bind(transaction_id).execute(pool).await;
                let result = match query_result {
                    Ok(result) => result,
                    Err(error) => {
                        return Err(crate::Error::Db(format!(
                            "cannot delete local DEX replay scope '{}' for transaction id '{}' on sqlite: {}",
                            scope_name, transaction_id, error
                        )));
                    },
                };
                deleted_count = deleted_count.saturating_add(result.rows_affected());
            }
            return Ok(deleted_count);
        },
    }
}

/// Updates the persisted payload of one decoded DEX event row.
pub async fn query_dex_decoded_events_update_payload_json_by_id(
    database: &crate::Database,
    decoded_event_id: i64,
    payload_json: &str,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let query_result = sqlx::query(
                r#"
UPDATE k_sol_dex_decoded_events
SET payload_json = ?
WHERE id = ?
                "#,
            )
            .bind(payload_json)
            .bind(decoded_event_id)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot update k_sol_dex_decoded_events payload_json by id '{}' on sqlite: {}",
                        decoded_event_id, 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
                    )));
                },
            }
        },
    }
}

/// Deletes decoded DEX instruction audit rows related to one decoded instruction.
///
/// This removes an audit row attached to the decoded instruction itself, its direct
/// parent instruction, or its direct child instructions inside the same transaction.
pub async fn query_dex_decoded_events_delete_related_instruction_audit(
    database: &crate::Database,
    transaction_id: i64,
    instruction_id: i64,
    audit_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 event_kind = ?
  AND instruction_id IN (
        SELECT id
        FROM k_sol_chain_instructions
        WHERE transaction_id = ?
          AND id = ?

        UNION

        SELECT parent_instruction_id
        FROM k_sol_chain_instructions
        WHERE transaction_id = ?
          AND id = ?
          AND parent_instruction_id IS NOT NULL

        UNION

        SELECT id
        FROM k_sol_chain_instructions
        WHERE transaction_id = ?
          AND parent_instruction_id = ?
      )
                "#,
            )
            .bind(transaction_id)
            .bind(audit_event_kind)
            .bind(transaction_id)
            .bind(instruction_id)
            .bind(transaction_id)
            .bind(instruction_id)
            .bind(transaction_id)
            .bind(instruction_id)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete related instruction audit events on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes Raydium CPMM instruction-audit rows for locally mapped CPMM instructions.
///
/// CPMM has one Anchor IDL-management instruction (`40f4bc78a7e9690a`) that is
/// decoded by the local Raydium audit-preservation pass rather than by the
/// CPMM instruction decoder itself because its payload is shorter than normal
/// CPMM instruction layouts. Once the named `raydium_cpmm.*` row exists, the
/// old `raydium_cpmm.instruction_audit` row is redundant and must be removed.
/// The allow-list also includes the regular CPMM instruction discriminators so
/// future replays do not leave duplicate audit rows for already covered entries.
pub async fn query_dex_decoded_events_delete_replaced_raydium_cpmm_instruction_audits(
    database: &crate::Database,
    transaction_id: std::option::Option<i64>,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let unlink_result = sqlx::query(
                r#"
UPDATE k_sol_instruction_observations
SET decoded_event_id = NULL
WHERE decoded_event_id IN (
    SELECT id
    FROM k_sol_dex_decoded_events
    WHERE protocol_name = 'raydium_cpmm'
      AND event_kind = 'raydium_cpmm.instruction_audit'
      AND (? IS NULL OR transaction_id = ?)
      AND (
            COALESCE(
              json_extract(payload_json, '$.discriminatorHex'),
              json_extract(payload_json, '$.discriminator_hex'),
              json_extract(payload_json, '$.instructionDiscriminatorHex'),
              json_extract(payload_json, '$.instruction_discriminator_hex')
            ) IN (
        '40f4bc78a7e9690a',
        '9c5420764587467b',
        '1416567bc61cdb84',
        'a78a4e95dfc2067e',
        '8888fcddc2427e59',
        'e445a52e51cb9a1d',
        '8934edd4d7756c68',
        '878802d889a9b5ca',
        'f223c68952e1f2b6',
        'afaf6d1f0d989bed',
        '3f37fe4131b25979',
        '8fbe5adac41e33de',
        '37d96256a34ab4ad',
        '313cae889a1c74c8',
        '82576c062ee0757b',
        'b712469c946da122'
          )
          OR instr(lower(COALESCE(payload_json, '')), '40f4bc78a7e9690a') > 0
          OR EXISTS (
                SELECT 1
                FROM k_sol_dex_decoded_events named
                WHERE named.transaction_id = k_sol_dex_decoded_events.transaction_id
                  AND named.protocol_name = 'raydium_cpmm'
                  AND named.event_kind = 'raydium_cpmm.anchor_idl_instruction'
              )
          )
)
                "#,
            )
            .bind(transaction_id)
            .bind(transaction_id)
            .execute(pool)
            .await;
            if let Err(error) = unlink_result {
                return Err(crate::Error::Db(format!(
                    "cannot unlink mapped Raydium CPMM instruction audit observations on sqlite: {}",
                    error
                )));
            }

            let query_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE protocol_name = 'raydium_cpmm'
  AND event_kind = 'raydium_cpmm.instruction_audit'
  AND (? IS NULL OR transaction_id = ?)
  AND (
        COALESCE(
          json_extract(payload_json, '$.discriminatorHex'),
          json_extract(payload_json, '$.discriminator_hex'),
          json_extract(payload_json, '$.instructionDiscriminatorHex'),
          json_extract(payload_json, '$.instruction_discriminator_hex')
        ) IN (
        '40f4bc78a7e9690a',
        '9c5420764587467b',
        '1416567bc61cdb84',
        'a78a4e95dfc2067e',
        '8888fcddc2427e59',
        'e445a52e51cb9a1d',
        '8934edd4d7756c68',
        '878802d889a9b5ca',
        'f223c68952e1f2b6',
        'afaf6d1f0d989bed',
        '3f37fe4131b25979',
        '8fbe5adac41e33de',
        '37d96256a34ab4ad',
        '313cae889a1c74c8',
        '82576c062ee0757b',
        'b712469c946da122'
      )
      OR instr(lower(COALESCE(payload_json, '')), '40f4bc78a7e9690a') > 0
      OR EXISTS (
            SELECT 1
            FROM k_sol_dex_decoded_events named
            WHERE named.transaction_id = k_sol_dex_decoded_events.transaction_id
              AND named.protocol_name = 'raydium_cpmm'
              AND named.event_kind = 'raydium_cpmm.anchor_idl_instruction'
          )
      )
                "#,
            )
            .bind(transaction_id)
            .bind(transaction_id)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete mapped Raydium CPMM instruction audit events on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes Raydium CLMM instruction-audit rows for locally mapped CLMM instructions.
///
/// The CLMM specialized decoder now emits named `raydium_clmm.*` rows for all
/// locally mapped instruction discriminants. Keeping the former
/// `raydium_clmm.instruction_audit` rows for the same discriminants creates
/// duplicate coverage and makes residual audit diagnostics noisy. Unknown
/// discriminants remain untouched because they are intentionally absent from
/// this allow-list.
pub async fn query_dex_decoded_events_delete_replaced_raydium_clmm_instruction_audits(
    database: &crate::Database,
    transaction_id: std::option::Option<i64>,
) -> 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 protocol_name = 'raydium_clmm'
  AND event_kind = 'raydium_clmm.instruction_audit'
  AND (? IS NULL OR transaction_id = ?)
  AND COALESCE(
        json_extract(payload_json, '$.discriminatorHex'),
        json_extract(payload_json, '$.discriminator_hex'),
        json_extract(payload_json, '$.instructionDiscriminatorHex'),
        json_extract(payload_json, '$.instruction_discriminator_hex')
      ) IN (
        '4c7c800fd55725fa',
        '9d20dab7471d1293',
        'b19059ecfaba7d63',
        '759d3c674231a300',
        '7b86510031446262',
        'c975989055556cb2',
        'a78a4e95dfc2067e',
        '8888fcddc2427e59',
        '12eda6c52210d590',
        '8934edd4d7756c68',
        '2b44d4a7592fa401',
        'bd0eb5785576e33e',
        '3f5794216d230868',
        'e992d18ecf6840bc',
        '11fb415c88f20ea9',
        'a026d06f685b2c01',
        '3a7fbc3e4f52c460',
        '2e9cf3760dcdfbb2',
        '851d59df45eeb00a',
        '5f87c0c4f281e644',
        '87802f4d0f98f031',
        '4db84ad67056f1c7',
        '4dffae527d1dc92e',
        '7034a74b20c9d389',
        'cd4e74215c691a60',
        'f8c69e91e17587c8',
        '457d73daf5baf2c4',
        '2b04ed0b1ac91e62',
        '07160c53f22b3079',
        '313cae889a1c74c8',
        '7f467728bce33d07',
        '82576c062ee0757b',
        'a3ace0340b9a6adf'
      )
                "#,
            )
            .bind(transaction_id)
            .bind(transaction_id)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete mapped Raydium CLMM instruction audit events on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes upstream registry instruction-match rows already covered by specialized local decoders.
///
/// The upstream registry fallback is useful only while an instruction is not yet
/// handled by a protocol-specific decoder. Once `k_sol_dex_event_coverage_entries`
/// has a non-empty `local_event_kind` for the same decoder/entry/discriminator,
/// the fallback row is redundant and must be removed so coverage queries do not
/// report both `upstream_git.instruction_match` and the local `protocol.*` event.
pub async fn query_dex_decoded_events_delete_locally_covered_upstream_instruction_matches(
    database: &crate::Database,
    upstream_decoder_code: std::option::Option<&str>,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let unlink_result = sqlx::query(
                r#"
UPDATE k_sol_instruction_observations
SET decoded_event_id = NULL
WHERE decoded_event_id IN (
    SELECT de.id
    FROM k_sol_dex_decoded_events de
    WHERE de.protocol_name = 'upstream_git'
      AND de.event_kind = 'upstream_git.instruction_match'
      AND (? IS NULL OR json_extract(de.payload_json, '$.upstreamDecoderCode') = ?)
      AND (
          COALESCE(json_extract(de.payload_json, '$.upstreamDecoderCode'), '')
          || '|'
          || COALESCE(json_extract(de.payload_json, '$.upstreamEntryName'), '')
          || '|'
          || COALESCE(json_extract(de.payload_json, '$.upstreamDiscriminatorHex'), '')
      ) IN (
          SELECT
              ce.decoder_code
              || '|'
              || ce.entry_name
              || '|'
              || ce.discriminator_hex
          FROM k_sol_dex_event_coverage_entries ce
          WHERE ce.local_event_kind IS NOT NULL
            AND ce.local_event_kind <> ''
            AND ce.discriminator_hex IS NOT NULL
            AND ce.discriminator_hex <> ''
      )
)
                "#,
            )
            .bind(upstream_decoder_code)
            .bind(upstream_decoder_code)
            .execute(pool)
            .await;
            if let Err(error) = unlink_result {
                return Err(crate::Error::Db(format!(
                    "cannot unlink locally covered upstream instruction matches from instruction observations on sqlite: {}",
                    error
                )));
            }

            let query_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE protocol_name = 'upstream_git'
  AND event_kind = 'upstream_git.instruction_match'
  AND (? IS NULL OR json_extract(payload_json, '$.upstreamDecoderCode') = ?)
  AND (
      COALESCE(json_extract(payload_json, '$.upstreamDecoderCode'), '')
      || '|'
      || COALESCE(json_extract(payload_json, '$.upstreamEntryName'), '')
      || '|'
      || COALESCE(json_extract(payload_json, '$.upstreamDiscriminatorHex'), '')
  ) IN (
      SELECT
          ce.decoder_code
          || '|'
          || ce.entry_name
          || '|'
          || ce.discriminator_hex
      FROM k_sol_dex_event_coverage_entries ce
      WHERE ce.local_event_kind IS NOT NULL
        AND ce.local_event_kind <> ''
        AND ce.discriminator_hex IS NOT NULL
        AND ce.discriminator_hex <> ''
  )
                "#,
            )
            .bind(upstream_decoder_code)
            .bind(upstream_decoder_code)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete locally covered upstream instruction matches on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes Meteora DLMM Anchor self-CPI swap audit rows already covered by decoded swaps.
///
/// This targets only local-corpus-observed Anchor event discriminators that are
/// decoded into `meteora_dlmm.swap` payload enrichment. It does not delete
/// unrelated DLMM instruction audits.
pub async fn query_dex_decoded_events_delete_meteora_dlmm_anchor_swap_instruction_audits(
    database: &crate::Database,
    transaction_id: i64,
) -> 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 protocol_name = 'meteora_dlmm'
  AND event_kind = 'meteora_dlmm.instruction_audit'
  AND json_extract(payload_json, '$.anchorSelfCpiLog') = 1
  AND json_extract(payload_json, '$.anchorEventDiscriminatorHex') IN (
        '516ce3becdd00ac4',
        '2e7452d7941b544d'
      )
                "#,
            )
            .bind(transaction_id)
            .execute(pool)
            .await;
            match query_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete Meteora DLMM Anchor swap audit events 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
                    )));
                },
            }
        },
    }
}

/// Deletes a Raydium CLMM instruction-audit row by discriminator for one transaction.
pub async fn query_dex_decoded_events_delete_raydium_clmm_instruction_audit_by_discriminator(
    database: &crate::Database,
    transaction_id: i64,
    discriminator_hex: &str,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let delete_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND protocol_name = 'raydium_clmm'
  AND event_kind = 'raydium_clmm.instruction_audit'
  AND (
        json_extract(payload_json, '$.discriminatorHex') = ?
     OR json_extract(payload_json, '$.discriminator_hex') = ?
     OR json_extract(payload_json, '$.instructionDiscriminatorHex') = ?
     OR json_extract(payload_json, '$.instruction_discriminator_hex') = ?
     OR json_extract(payload_json, '$.anchorEventDiscriminatorHex') = ?
     OR json_extract(payload_json, '$.anchor_event_discriminator_hex') = ?
      )
                "#,
            )
            .bind(transaction_id)
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .execute(pool)
            .await;
            match delete_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete Raydium CLMM residual instruction audit '{}': {}",
                        discriminator_hex, error
                    )));
                },
            }
        },
    }
}

/// Deletes a protocol instruction-audit row by discriminator for one transaction.
pub async fn query_dex_decoded_events_delete_instruction_audit_by_discriminator(
    database: &crate::Database,
    transaction_id: i64,
    protocol_name: &str,
    audit_event_kind: &str,
    discriminator_hex: &str,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let delete_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND protocol_name = ?
  AND event_kind = ?
  AND (
        json_extract(payload_json, '$.discriminatorHex') = ?
     OR json_extract(payload_json, '$.discriminator_hex') = ?
     OR json_extract(payload_json, '$.instructionDiscriminatorHex') = ?
     OR json_extract(payload_json, '$.instruction_discriminator_hex') = ?
     OR json_extract(payload_json, '$.anchorEventDiscriminatorHex') = ?
     OR json_extract(payload_json, '$.anchor_event_discriminator_hex') = ?
     OR instr(lower(COALESCE(payload_json, '')), lower(?)) > 0
      )
                "#,
            )
            .bind(transaction_id)
            .bind(protocol_name.to_string())
            .bind(audit_event_kind.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .bind(discriminator_hex.to_string())
            .execute(pool)
            .await;
            match delete_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete replaced instruction audit by discriminator on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes a Raydium Launchpad self-CPI audit row replaced by a direct decoded event.
pub async fn query_dex_decoded_events_delete_raydium_launchpad_anchor_self_cpi_audit(
    database: &crate::Database,
    transaction_id: i64,
    anchor_self_cpi_log_selector_hex: &str,
    anchor_event_discriminator_hex: &str,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let delete_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE transaction_id = ?
  AND protocol_name = 'raydium_launchpad'
  AND event_kind = 'raydium_launchpad.instruction_audit'
  AND json_extract(payload_json, '$.anchorSelfCpiLog') = 1
  AND json_extract(payload_json, '$.anchorSelfCpiLogSelectorHex') = ?
  AND json_extract(payload_json, '$.anchorEventDiscriminatorHex') = ?
                "#,
            )
            .bind(transaction_id)
            .bind(anchor_self_cpi_log_selector_hex.to_string())
            .bind(anchor_event_discriminator_hex.to_string())
            .execute(pool)
            .await;
            match delete_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot delete replaced Raydium Launchpad self-CPI instruction audit on sqlite: {}",
                        error
                    )));
                },
            }
        },
    }
}

/// Deletes Raydium Launchpad self-CPI audit rows once their direct decoded rows exist.
pub async fn query_dex_decoded_events_cleanup_raydium_launchpad_anchor_self_cpi_audits(
    database: &crate::Database,
    transaction_id: i64,
    anchor_self_cpi_log_selector_hex: &str,
) -> Result<u64, crate::Error> {
    match database.connection() {
        crate::DatabaseConnection::Sqlite(pool) => {
            let delete_result = sqlx::query(
                r#"
DELETE FROM k_sol_dex_decoded_events
WHERE id IN (
    SELECT audit.id
    FROM k_sol_dex_decoded_events audit
    WHERE audit.transaction_id = ?
      AND audit.protocol_name = 'raydium_launchpad'
      AND audit.event_kind = 'raydium_launchpad.instruction_audit'
      AND json_extract(audit.payload_json, '$.anchorSelfCpiLog') = 1
      AND json_extract(audit.payload_json, '$.anchorSelfCpiLogSelectorHex') = ?
      AND EXISTS (
          SELECT 1
          FROM k_sol_dex_decoded_events direct
          WHERE direct.transaction_id = audit.transaction_id
            AND direct.protocol_name = 'raydium_launchpad'
            AND direct.event_kind IN (
                'raydium_launchpad.trade_event',
                'raydium_launchpad.pool_create_event',
                'raydium_launchpad.claim_vested_event',
                'raydium_launchpad.create_vesting_event'
            )
            AND json_extract(direct.payload_json, '$.anchorEventDiscriminatorHex') =
                json_extract(audit.payload_json, '$.anchorEventDiscriminatorHex')
      )
)
                "#,
            )
            .bind(transaction_id)
            .bind(anchor_self_cpi_log_selector_hex.to_string())
            .execute(pool)
            .await;
            match delete_result {
                Ok(result) => return Ok(result.rows_affected()),
                Err(error) => {
                    return Err(crate::Error::Db(format!(
                        "cannot cleanup replaced Raydium Launchpad self-CPI instruction audits on sqlite: {}",
                        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");
    }

    #[tokio::test]
    async fn related_instruction_audit_delete_removes_parent_audit_for_child_decode() {
        let database = make_database().await;
        let transaction_dto = crate::ChainTransactionDto::new(
            "sig-dex-event-related-audit-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 parent_instruction_dto = crate::ChainInstructionDto::new(
            transaction_id,
            None,
            0,
            None,
            Some(crate::METEORA_DLMM_PROGRAM_ID.to_string()),
            Some("meteora_dlmm".to_string()),
            Some(1),
            r#"["ParentAccount","Pool111"]"#.to_string(),
            None,
            None,
            None,
        );
        let parent_instruction_id_result =
            crate::query_chain_instructions_insert(&database, &parent_instruction_dto).await;
        let parent_instruction_id = match parent_instruction_id_result {
            Ok(parent_instruction_id) => parent_instruction_id,
            Err(error) => panic!("parent instruction insert must succeed: {}", error),
        };
        let child_instruction_dto = crate::ChainInstructionDto::new(
            transaction_id,
            Some(parent_instruction_id),
            0,
            Some(0),
            Some(crate::METEORA_DLMM_PROGRAM_ID.to_string()),
            Some("meteora_dlmm".to_string()),
            Some(2),
            r#"["ChildAccount","Pool111"]"#.to_string(),
            None,
            None,
            None,
        );
        let child_instruction_id_result =
            crate::query_chain_instructions_insert(&database, &child_instruction_dto).await;
        let child_instruction_id = match child_instruction_id_result {
            Ok(child_instruction_id) => child_instruction_id,
            Err(error) => panic!("child instruction insert must succeed: {}", error),
        };
        let audit_dto = crate::DexDecodedEventDto::new(
            transaction_id,
            Some(parent_instruction_id),
            "meteora_dlmm".to_string(),
            crate::METEORA_DLMM_PROGRAM_ID.to_string(),
            "meteora_dlmm.instruction_audit".to_string(),
            Some("Pool111".to_string()),
            None,
            None,
            None,
            None,
            r#"{"audit":true}"#.to_string(),
        );
        let audit_upsert_result =
            crate::query_dex_decoded_events_upsert(&database, &audit_dto).await;
        match audit_upsert_result {
            Ok(_) => {},
            Err(error) => panic!("audit upsert must succeed: {}", error),
        }
        let deleted_result = super::query_dex_decoded_events_delete_related_instruction_audit(
            &database,
            transaction_id,
            child_instruction_id,
            "meteora_dlmm.instruction_audit",
        )
        .await;
        let deleted = match deleted_result {
            Ok(deleted) => deleted,
            Err(error) => panic!("related audit delete must succeed: {}", error),
        };
        assert_eq!(deleted, 1);
        let fetched_result = crate::query_dex_decoded_events_get_by_key(
            &database,
            transaction_id,
            Some(parent_instruction_id),
            "meteora_dlmm.instruction_audit",
        )
        .await;
        let fetched = match fetched_result {
            Ok(fetched) => fetched,
            Err(error) => panic!("audit fetch must succeed: {}", error),
        };
        assert!(fetched.is_none());
    }
}
