mod program_test;
use {
    mpl_token_metadata::accounts::{MasterEdition, Metadata},
    program_test::StablebondProgramTest,
    solana_program_test::{tokio, ProgramTestContext},
    solana_sdk::{
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        transaction::Transaction,
    },
    spl_associated_token_account::get_associated_token_address,
    spl_token_2022::{
        extension::{
            interest_bearing_mint::InterestBearingConfig, BaseStateWithExtensions,
            StateWithExtensionsOwned,
        },
        state::Mint,
    },
    stablebond_sdk::{
        accounts::Bond,
        find_bond_pda, find_config_pda, find_delegate_pda, find_payment_feed_pda,
        instructions::{
            InitializeBond, InitializeBondInstructionArgs, InitializeConfig,
            InitializeConfigInstructionArgs, InitializeDelegate, UpdateBondMetadata,
            UpdateBondMetadataInstructionArgs,
        },
        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_bond_metadata() {
    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());

    //validate bond account
    let account = et
        .context
        .banks_client
        .get_account(find_bond_pda(et.bond_mint.pubkey()).0)
        .await
        .unwrap();

    assert!(account.is_some());
    let account = account.unwrap();
    assert_eq!(account.data.len(), 56);
    let bond: Bond = Bond::from_bytes(account.data.as_slice()).unwrap();
    assert_eq!(bond.discriminator, Discriminator::Bond);
    assert_eq!(bond.mint, et.bond_mint.pubkey());
    assert_eq!(bond.version, 1);
    assert_eq!(bond.payment_feed_type, PaymentFeedType::UsdcUsd);
    assert_eq!(bond.bond_fee_bps, 0);
    assert_eq!(bond.issuance_number, 0);
    assert_eq!(bond.cutoff_in_seconds, 86400);

    //validate mint account
    let account = et
        .context
        .banks_client
        .get_account(et.bond_mint.pubkey())
        .await
        .unwrap()
        .unwrap();

    let mint_account = StateWithExtensionsOwned::<Mint>::unpack(account.data).unwrap();
    let extension = mint_account
        .get_extension::<InterestBearingConfig>()
        .unwrap();
    assert_eq!(account.owner, spl_token_2022::id());
    assert_eq!(i16::from(extension.current_rate), 0);
    assert_eq!(
        Option::<Pubkey>::from(extension.rate_authority),
        Some(find_bond_pda(et.bond_mint.pubkey()).0)
    );

    let metadata_account = Metadata::find_pda(&et.bond_mint.pubkey()).0;
    let account = et
        .context
        .banks_client
        .get_account(metadata_account)
        .await
        .unwrap()
        .unwrap();

    let metadata = Metadata::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(metadata.name.trim_end_matches('\0'), "Test Mint");
    assert_eq!(metadata.symbol.trim_end_matches('\0'), "TM");
    assert_eq!(metadata.uri.trim_end_matches('\0'), "https://test.com");

    let new_name = "New Name".to_string();
    let update_bond_metadata_ix_args = UpdateBondMetadataInstructionArgs {
        name: Some(new_name.clone()),
        symbol: None,
    };

    let update_bond_metadata_ix = UpdateBondMetadata {
        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_account,
        metadata_program: mpl_token_metadata::ID,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_metadata_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_bond_metadata_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(metadata_account)
        .await
        .unwrap()
        .unwrap();

    let metadata = Metadata::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(metadata.name.trim_end_matches('\0'), new_name);
    assert_eq!(metadata.symbol.trim_end_matches('\0'), "TM");
    assert_eq!(metadata.uri.trim_end_matches('\0'), "https://test.com");

    let new_symbol = "NST".to_string();
    let update_bond_metadata_ix_args = UpdateBondMetadataInstructionArgs {
        name: None,
        symbol: Some(new_symbol.clone()),
    };

    let update_bond_metadata_ix = UpdateBondMetadata {
        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_account,
        metadata_program: mpl_token_metadata::ID,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_metadata_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_bond_metadata_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(metadata_account)
        .await
        .unwrap()
        .unwrap();

    let metadata = Metadata::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(metadata.name.trim_end_matches('\0'), new_name);
    assert_eq!(metadata.symbol.trim_end_matches('\0'), new_symbol);
    assert_eq!(metadata.uri.trim_end_matches('\0'), "https://test.com");

    let new_name = "JAHJAH".to_string();
    let new_symbol = "JAH".to_string();
    let update_bond_metadata_ix_args = UpdateBondMetadataInstructionArgs {
        name: Some(new_name.clone()),
        symbol: Some(new_symbol.clone()),
    };

    let update_bond_metadata_ix = UpdateBondMetadata {
        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_account,
        metadata_program: mpl_token_metadata::ID,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_metadata_ix_args);

    let transaction = Transaction::new_signed_with_payer(
        &[update_bond_metadata_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(metadata_account)
        .await
        .unwrap()
        .unwrap();

    let metadata = Metadata::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(metadata.name.trim_end_matches('\0'), new_name);
    assert_eq!(metadata.symbol.trim_end_matches('\0'), new_symbol);
    assert_eq!(metadata.uri.trim_end_matches('\0'), "https://test.com");

    let old_name = new_name.clone();
    let old_symbol = new_symbol.clone();
    let update_bond_metadata_ix_args = UpdateBondMetadataInstructionArgs {
        name: None,
        symbol: None,
    };

    let update_bond_metadata_ix = UpdateBondMetadata {
        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_account,
        metadata_program: mpl_token_metadata::ID,
        system_program: solana_program::system_program::id(),
    }
    .instruction(update_bond_metadata_ix_args);

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

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

    let account = et
        .context
        .banks_client
        .get_account(metadata_account)
        .await
        .unwrap()
        .unwrap();

    let metadata = Metadata::from_bytes(&account.data.borrow()).unwrap();
    assert_eq!(metadata.name.trim_end_matches('\0'), old_name);
    assert_eq!(metadata.symbol.trim_end_matches('\0'), old_symbol);
    assert_eq!(metadata.uri.trim_end_matches('\0'), "https://test.com");
}
