use anyhow::Result;
use riptide_amm::{fetch_market, MarketUpdate, MarketUpdateInstructionArgs, MarketUpdateType};
use solana_pubkey::Pubkey;

use crate::{config::Config, log_context, transaction::process_instructions};

pub fn handle(config: &Config, market: &Pubkey, update: &MarketUpdateType) -> Result<()> {
    let rpc = config.rpc_client();

    let market_account = fetch_market(&rpc, market)?;
    let authority = market_account.data.authority;
    let signer = config
        .authority(&authority)
        .ok_or(anyhow::anyhow!("Authority not found"))?;

    let ixs = [MarketUpdate {
        authority,
        market: *market,
        system_program: solana_system_interface::program::ID,
    }
    .instruction(MarketUpdateInstructionArgs {
        update: update.clone(),
    })];

    log_context!(
        market => market,
        authority => authority,
        update => update,
    );

    process_instructions(&rpc, &[signer], &ixs)
}
