mod program_test;
use {
    mpl_token_metadata::accounts::{MasterEdition, Metadata},
    program_test::StablebondProgramTest,
    solana_program_test::{tokio, ProgramTestContext},
    solana_sdk::{
        signature::{Keypair, Signer},
        transaction::Transaction,
    },
    spl_associated_token_account::get_associated_token_address,
    stablebond_sdk::{
        accounts::PaymentFeed,
        find_bond_pda, find_config_pda, find_delegate_pda, find_payment_feed_pda,
        instructions::{
            InitializeBond, InitializeBondInstructionArgs, InitializeConfig,
            InitializeConfigInstructionArgs, InitializeDelegate, UpdatePaymentFeed,
            UpdatePaymentFeedInstructionArgs,
        },
        types::{Discriminator, OracleSetup, PaymentFeedType},
    },
    std::borrow::Borrow,
};

struct ExecuteTestContext {
    context: ProgramTestContext,
    admin: Keypair,
    bond_mint: Keypair,
}

async fn setup() -> ExecuteTestContext {
    let pt = StablebondProgramTest::start_new().await;
    let bond_mint = pt.bond_mints[0].insecure_clone();
    let admin = pt.admin;
    let nft_collection_mint = pt.nft_collection_mint;

    let initialize_config_ix_args = InitializeConfigInstructionArgs {
        oracle: OracleSetup::Stub,
        usdc_mxn_payment_feed: pt.usdc_mxn_payment_feed.clone(),
        usdc_usd_payment_feed: pt.usdc_usd_payment_feed,
    };

    let initialize_config_ix = InitializeConfig {
        admin_wallet: admin.pubkey(),
        config_account: find_config_pda().0,
        config_token_account: get_associated_token_address(
            &find_config_pda().0,
            &nft_collection_mint.pubkey(),
        ),
        mint_account: nft_collection_mint.pubkey(),
        payment_mint_account: pt.usdc_mxn_payment_feed.payment_mint,
        metadata_account: Metadata::find_pda(&nft_collection_mint.pubkey()).0,
        master_edition_account: MasterEdition::find_pda(&nft_collection_mint.pubkey()).0,
        usdc_mxn_feed_account: find_payment_feed_pda(PaymentFeedType::UsdcMxn).0,
        usdc_usd_feed_account: find_payment_feed_pda(PaymentFeedType::UsdcUsd).0,
        token_program: spl_token::id(),
        associated_token_program: spl_associated_token_account::id(),
        metadata_program: mpl_token_metadata::ID,
        system_program: solana_program::system_program::id(),
    }
    .instruction(initialize_config_ix_args);

    let initialize_delegate_ix = InitializeDelegate {
        config_account: find_config_pda().0,
        admin_wallet: admin.pubkey(),
        delegate_wallet: admin.pubkey(),
        delegate_account: find_delegate_pda(admin.pubkey()).0,
        system_program: solana_program::system_program::id(),
    }
    .instruction();

    let ixs = &[initialize_config_ix, initialize_delegate_ix];

    let mut context = pt.context;
    let transaction = Transaction::new_signed_with_payer(
        ixs,
        Some(&admin.pubkey()),
        &[&admin, &nft_collection_mint],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();
    ExecuteTestContext {
        context,
        admin,
        bond_mint,
    }
}

#[tokio::test]
async fn update_payment_feed() {
    let mut et = setup().await;

    let initialize_bond_ix_args = InitializeBondInstructionArgs {
        name: "Test Mint".to_string(),
        symbol: "TM".to_string(),
        uri: "https://test.com".to_string(),
        payment_feed_type: PaymentFeedType::UsdcUsd,
        cutoff_in_seconds: 60 * 60 * 24,
    };

    let initialize_bond_ix = InitializeBond {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        mint_account: et.bond_mint.pubkey(),
        metadata_account: Metadata::find_pda(&et.bond_mint.pubkey()).0,
        token2022_program: spl_token_2022::id(),
        metadata_program: mpl_token_metadata::ID,
        sysvar_instructions: solana_program::sysvar::instructions::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction(initialize_bond_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[initialize_bond_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin, &et.bond_mint],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let new_base_price_feed = Keypair::new();
    let new_quote_price_feed = Keypair::new();
    let update_bond_name_ix_args = UpdatePaymentFeedInstructionArgs {
        base_price_feed: Some(new_base_price_feed.pubkey()),
        quote_price_feed: Some(new_quote_price_feed.pubkey()),
    };

    let update_payment_feed_ix = UpdatePaymentFeed {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        payment_feed_account: find_payment_feed_pda(PaymentFeedType::UsdcUsd).0,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_name_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_payment_feed_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let account = et
        .context
        .banks_client
        .get_account(find_payment_feed_pda(PaymentFeedType::UsdcUsd).0)
        .await
        .unwrap()
        .unwrap();

    let payment_feed: PaymentFeed = PaymentFeed::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(payment_feed.discriminator, Discriminator::PaymentFeed);
    assert_eq!(payment_feed.base_price_feed, new_base_price_feed.pubkey());
    assert_eq!(payment_feed.quote_price_feed, new_quote_price_feed.pubkey());
}

#[tokio::test]
async fn update_payment_feed_only_base_price_feed() {
    let mut et = setup().await;

    let initialize_bond_ix_args = InitializeBondInstructionArgs {
        name: "Test Mint".to_string(),
        symbol: "TM".to_string(),
        uri: "https://test.com".to_string(),
        payment_feed_type: PaymentFeedType::UsdcUsd,
        cutoff_in_seconds: 60 * 60 * 24,
    };

    let initialize_bond_ix = InitializeBond {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        mint_account: et.bond_mint.pubkey(),
        metadata_account: Metadata::find_pda(&et.bond_mint.pubkey()).0,
        token2022_program: spl_token_2022::id(),
        metadata_program: mpl_token_metadata::ID,
        sysvar_instructions: solana_program::sysvar::instructions::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction(initialize_bond_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[initialize_bond_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin, &et.bond_mint],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let account = et
        .context
        .banks_client
        .get_account(find_payment_feed_pda(PaymentFeedType::UsdcUsd).0)
        .await
        .unwrap()
        .unwrap();

    let old_payment_feed: PaymentFeed = PaymentFeed::from_bytes(&account.data.borrow()).unwrap();

    let new_base_price_feed = Keypair::new();
    let update_bond_name_ix_args = UpdatePaymentFeedInstructionArgs {
        base_price_feed: Some(new_base_price_feed.pubkey()),
        quote_price_feed: None,
    };

    let update_payment_feed_ix = UpdatePaymentFeed {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        payment_feed_account: find_payment_feed_pda(PaymentFeedType::UsdcUsd).0,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_name_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_payment_feed_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let account = et
        .context
        .banks_client
        .get_account(find_payment_feed_pda(PaymentFeedType::UsdcUsd).0)
        .await
        .unwrap()
        .unwrap();

    let payment_feed: PaymentFeed = PaymentFeed::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(payment_feed.discriminator, Discriminator::PaymentFeed);
    assert_eq!(payment_feed.base_price_feed, new_base_price_feed.pubkey());
    assert_eq!(
        payment_feed.quote_price_feed,
        old_payment_feed.quote_price_feed
    );
    assert_ne!(
        payment_feed.base_price_feed,
        old_payment_feed.base_price_feed
    );
}

#[tokio::test]
async fn update_payment_feed_only_quote_price_feed() {
    let mut et = setup().await;

    let initialize_bond_ix_args = InitializeBondInstructionArgs {
        name: "Test Mint".to_string(),
        symbol: "TM".to_string(),
        uri: "https://test.com".to_string(),
        payment_feed_type: PaymentFeedType::UsdcUsd,
        cutoff_in_seconds: 60 * 60 * 24,
    };

    let initialize_bond_ix = InitializeBond {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        mint_account: et.bond_mint.pubkey(),
        metadata_account: Metadata::find_pda(&et.bond_mint.pubkey()).0,
        token2022_program: spl_token_2022::id(),
        metadata_program: mpl_token_metadata::ID,
        sysvar_instructions: solana_program::sysvar::instructions::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction(initialize_bond_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[initialize_bond_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin, &et.bond_mint],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let account = et
        .context
        .banks_client
        .get_account(find_payment_feed_pda(PaymentFeedType::UsdcUsd).0)
        .await
        .unwrap()
        .unwrap();

    let old_payment_feed: PaymentFeed = PaymentFeed::from_bytes(&account.data.borrow()).unwrap();

    let new_quote_price_feed = Keypair::new();
    let update_bond_name_ix_args = UpdatePaymentFeedInstructionArgs {
        base_price_feed: None,
        quote_price_feed: Some(new_quote_price_feed.pubkey()),
    };

    let update_payment_feed_ix = UpdatePaymentFeed {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        payment_feed_account: find_payment_feed_pda(PaymentFeedType::UsdcUsd).0,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_name_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_payment_feed_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let account = et
        .context
        .banks_client
        .get_account(find_payment_feed_pda(PaymentFeedType::UsdcUsd).0)
        .await
        .unwrap()
        .unwrap();

    let payment_feed: PaymentFeed = PaymentFeed::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(payment_feed.discriminator, Discriminator::PaymentFeed);
    assert_eq!(
        payment_feed.base_price_feed,
        old_payment_feed.base_price_feed
    );
    assert_eq!(payment_feed.quote_price_feed, new_quote_price_feed.pubkey());
    assert_ne!(
        payment_feed.quote_price_feed,
        old_payment_feed.quote_price_feed
    );
}

#[tokio::test]
async fn fail_update_payment_feed_both_price_feeds_none() {
    let mut et = setup().await;

    let initialize_bond_ix_args = InitializeBondInstructionArgs {
        name: "Test Mint".to_string(),
        symbol: "TM".to_string(),
        uri: "https://test.com".to_string(),
        payment_feed_type: PaymentFeedType::UsdcUsd,
        cutoff_in_seconds: 60 * 60 * 24,
    };

    let initialize_bond_ix = InitializeBond {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        mint_account: et.bond_mint.pubkey(),
        metadata_account: Metadata::find_pda(&et.bond_mint.pubkey()).0,
        token2022_program: spl_token_2022::id(),
        metadata_program: mpl_token_metadata::ID,
        sysvar_instructions: solana_program::sysvar::instructions::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction(initialize_bond_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[initialize_bond_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin, &et.bond_mint],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_ok());

    let update_bond_name_ix_args = UpdatePaymentFeedInstructionArgs {
        base_price_feed: None,
        quote_price_feed: None,
    };

    let update_payment_feed_ix = UpdatePaymentFeed {
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        delegate_wallet: et.admin.pubkey(),
        payment_feed_account: find_payment_feed_pda(PaymentFeedType::UsdcUsd).0,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_name_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_payment_feed_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        et.context.last_blockhash,
    );

    assert!(et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .is_err());
}
