mod program_test;
use {
    mpl_token_metadata::accounts::{MasterEdition, Metadata},
    program_test::StablebondProgramTest,
    solana_program_test::{tokio, ProgramTestContext},
    solana_sdk::{
        instruction::InstructionError,
        program_pack::Pack,
        signature::{Keypair, Signer},
        transaction::{Transaction, TransactionError},
    },
    spl_associated_token_account::{
        get_associated_token_address, get_associated_token_address_with_program_id,
    },
    spl_token_2022::state::Account as Token2022Account,
    stablebond_sdk::{
        accounts::Offramp,
        errors::StablebondError,
        find_bond_pda, find_config_pda, find_delegate_pda, find_issuance_pda, find_offramp_pda,
        find_onramp_pda, find_payment_feed_pda, find_payment_pda, find_payout_pda,
        instructions::{
            BurnBondFromTokenAmount, BurnBondFromTokenAmountInstructionArgs,
            DelegateMintBondFromTokenAmount, DelegateMintBondFromTokenAmountInstructionArgs,
            InitializeBond, InitializeBondInstructionArgs, InitializeConfig,
            InitializeConfigInstructionArgs, InitializeDelegate, InitializeIssuance,
            InitializeIssuanceInstructionArgs, InitializePaymentFeed,
            InitializePaymentFeedInstructionArgs, StartIssuance, UpdateOfframpToCompleted,
        },
        types::{Discriminator, OfframpStatus, OracleSetup, PaymentFeedType},
    },
    std::time::{SystemTime, UNIX_EPOCH},
};

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

async fn setup() -> ExecuteTestContext {
    let pt = StablebondProgramTest::start_new().await;
    let usdc_mint = pt.mints[0].payment_mint;
    let bond_mint = pt.bond_mints[0].insecure_clone();
    let admin = pt.admin;
    let user = pt.users[0].insecure_clone();
    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 initialize_payment_feed_args = InitializePaymentFeedInstructionArgs {
        payment_feed_info: pt.stub_payment_feed,
    };

    let initialize_payment_feed_ix = InitializePaymentFeed {
        delegate_wallet: admin.pubkey(),
        delegate_account: find_delegate_pda(admin.pubkey()).0,
        payment_feed_account: find_payment_feed_pda(PaymentFeedType::Stub).0,
        payment_mint_account: usdc_mint,
        system_program: solana_program::system_program::id(),
    }
    .instruction(initialize_payment_feed_args);

    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::Stub,
        cutoff_in_seconds: 60 * 60 * 24,
    };

    let initialize_bond_ix = InitializeBond {
        delegate_account: find_delegate_pda(admin.pubkey()).0,
        delegate_wallet: admin.pubkey(),
        bond_account: find_bond_pda(bond_mint.pubkey()).0,
        mint_account: bond_mint.pubkey(),
        metadata_account: Metadata::find_pda(&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 current_time = StablebondProgramTest::get_current_time();
    let one_minute_ago: i64 = current_time - 60;
    let two_days_from_now: i64 = 60 * 60 * 24 * 2;

    let initialize_issuance_ix_args = InitializeIssuanceInstructionArgs {
        liquidity: 100_000_000,
        interest_rate_bps: 11_00,
        estimated_start_datetime: one_minute_ago,
        length_in_seconds: two_days_from_now,
    };

    let issuance_number = 1;
    let bond_pda = find_bond_pda(bond_mint.pubkey()).0;
    let issuance_pda = find_issuance_pda(bond_pda, issuance_number).0;
    let payment_pda = find_payment_pda(issuance_pda).0;
    let payout_pda = find_payout_pda(issuance_pda).0;
    let initialize_issuance_ix = InitializeIssuance {
        delegate_wallet: admin.pubkey(),
        delegate_account: find_delegate_pda(admin.pubkey()).0,
        bond_account: find_bond_pda(bond_mint.pubkey()).0,
        upcoming_issuance_account: issuance_pda,
        payment_feed_account: find_payment_feed_pda(PaymentFeedType::Stub).0,
        payment_mint_account: usdc_mint,
        payment_account: payment_pda,
        payment_token_account: get_associated_token_address(&payment_pda, &usdc_mint),
        payout_account: payout_pda,
        payout_token_account: get_associated_token_address(&payout_pda, &usdc_mint),
        associated_token_program: spl_associated_token_account::id(),
        token_program: spl_token::id(),
        system_program: solana_program::system_program::id(),
        current_issuance_account: None,
    }
    .instruction(initialize_issuance_ix_args);

    let start_issuance_ix = StartIssuance {
        delegate_account: find_delegate_pda(admin.pubkey()).0,
        delegate_wallet: admin.pubkey(),
        bond_account: find_bond_pda(bond_mint.pubkey()).0,
        issuance_account: find_issuance_pda(find_bond_pda(bond_mint.pubkey()).0, 1).0,
        mint_account: bond_mint.pubkey(),
        token2022_program: spl_token_2022::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction();

    let mut external_identifier = [0; 16];
    external_identifier[0] = 1;
    let onramp_pda = find_onramp_pda(&external_identifier).0;
    let delegate_mint_bond_ix_args = DelegateMintBondFromTokenAmountInstructionArgs {
        amount: 100_000,
        external_identifier,
    };
    let delegate_mint_bond_ix = DelegateMintBondFromTokenAmount {
        delegate_wallet: admin.pubkey(),
        delegate_account: find_delegate_pda(admin.pubkey()).0,
        bond_account: find_bond_pda(bond_mint.pubkey()).0,
        issuance_account: find_issuance_pda(find_bond_pda(bond_mint.pubkey()).0, 1).0,
        mint_account: bond_mint.pubkey(),
        user_wallet: user.pubkey(),
        user_token_account: get_associated_token_address_with_program_id(
            &user.pubkey(),
            &bond_mint.pubkey(),
            &spl_token_2022::id(),
        ),
        onramp_account: onramp_pda,
        token2022_program: spl_token_2022::id(),
        associated_token_program: spl_associated_token_account::id(),
        token_program: spl_token::id(),
        system_program: solana_program::system_program::id(),
        mint_auth_multisig_account: None,
    }
    .instruction(delegate_mint_bond_ix_args);

    let ixs = &[
        initialize_config_ix,
        initialize_delegate_ix,
        initialize_payment_feed_ix,
        initialize_bond_ix,
        initialize_issuance_ix,
        start_issuance_ix,
    ];

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

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    let ix = &[delegate_mint_bond_ix];
    let new_blockhash = context.banks_client.get_latest_blockhash().await.unwrap();
    let transaction =
        Transaction::new_signed_with_payer(ix, Some(&admin.pubkey()), &[&admin], new_blockhash);
    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    ExecuteTestContext {
        context,
        user,
        admin,
        bond_mint,
    }
}

#[tokio::test]
async fn update_offramp_to_completed() {
    let mut et = setup().await;
    let amount = 100_000;
    let mut external_identifier = [0; 16];
    external_identifier[0] = 1;
    let burn_bond_ix_args = BurnBondFromTokenAmountInstructionArgs {
        amount,
        external_identifier,
    };
    let offramp_pda = find_offramp_pda(&external_identifier).0;

    let user_bond_token_account_address = get_associated_token_address_with_program_id(
        &et.user.pubkey(),
        &et.bond_mint.pubkey(),
        &spl_token_2022::id(),
    );
    let user_bond_token_account = et
        .context
        .banks_client
        .get_account(user_bond_token_account_address)
        .await
        .unwrap();
    assert!(user_bond_token_account.is_some());
    let user_bond_amount_before =
        Token2022Account::unpack_from_slice(&user_bond_token_account.unwrap().data)
            .unwrap()
            .amount;
    let burn_bond_ix = BurnBondFromTokenAmount {
        delegate_wallet: et.admin.pubkey(),
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        issuance_account: find_issuance_pda(find_bond_pda(et.bond_mint.pubkey()).0, 1).0,
        mint_account: et.bond_mint.pubkey(),
        user_wallet: et.user.pubkey(),
        user_token_account: get_associated_token_address_with_program_id(
            &et.user.pubkey(),
            &et.bond_mint.pubkey(),
            &spl_token_2022::id(),
        ),
        offramp_account: offramp_pda,
        token2022_program: spl_token_2022::id(),
        associated_token_program: spl_associated_token_account::id(),
        token_program: spl_token::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction(burn_bond_ix_args);

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

    let res = et
        .context
        .banks_client
        .process_transaction(transaction)
        .await;

    assert!(res.is_ok());
    let user_bond_token_account = et
        .context
        .banks_client
        .get_account(user_bond_token_account_address)
        .await
        .unwrap();

    let user_bond_token_account =
        Token2022Account::unpack_from_slice(&user_bond_token_account.unwrap().data).unwrap();
    assert_eq!(
        user_bond_token_account.amount,
        user_bond_amount_before - amount
    );

    let offramp_account = et
        .context
        .banks_client
        .get_account(offramp_pda)
        .await
        .unwrap()
        .unwrap();

    let offramp = Offramp::from_bytes(&offramp_account.data).unwrap();
    assert_eq!(offramp.discriminator, Discriminator::Offramp);
    assert_eq!(offramp.version, 1);
    assert_eq!(offramp.external_identifier, external_identifier);
    assert_eq!(offramp.wallet, et.user.pubkey());
    assert_eq!(offramp.bond, find_bond_pda(et.bond_mint.pubkey()).0);
    assert_eq!(offramp.status, OfframpStatus::Processing);
    assert!(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64
            >= offramp.time
    );

    let update_offramp_to_completed_ix = UpdateOfframpToCompleted {
        delegate_wallet: et.admin.pubkey(),
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        offramp_account: offramp_pda,
        system_program: solana_program::system_program::id(),
    }
    .instruction();

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

    let res = et
        .context
        .banks_client
        .process_transaction(transaction)
        .await;

    assert!(res.is_ok());

    let offramp_account = et
        .context
        .banks_client
        .get_account(offramp_pda)
        .await
        .unwrap()
        .unwrap();

    let offramp = Offramp::from_bytes(&offramp_account.data).unwrap();
    assert_eq!(offramp.discriminator, Discriminator::Offramp);
    assert_eq!(offramp.version, 1);
    assert_eq!(offramp.external_identifier, external_identifier);
    assert_eq!(offramp.wallet, et.user.pubkey());
    assert_eq!(offramp.bond, find_bond_pda(et.bond_mint.pubkey()).0);
    assert_eq!(offramp.status, OfframpStatus::Completed);
}

#[tokio::test]
async fn fail_update_offramp_to_completed_when_delegate_doesnt_sign() {
    let mut et = setup().await;
    let amount = 100_000;
    let mut external_identifier = [0; 16];
    external_identifier[0] = 1;
    let burn_bond_ix_args = BurnBondFromTokenAmountInstructionArgs {
        amount,
        external_identifier,
    };
    let offramp_pda = find_offramp_pda(&external_identifier).0;
    let fake_delegate = Keypair::new();

    let burn_bond_ix = BurnBondFromTokenAmount {
        delegate_wallet: et.admin.pubkey(),
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        issuance_account: find_issuance_pda(find_bond_pda(et.bond_mint.pubkey()).0, 1).0,
        mint_account: et.bond_mint.pubkey(),
        user_wallet: et.user.pubkey(),
        user_token_account: get_associated_token_address_with_program_id(
            &et.user.pubkey(),
            &et.bond_mint.pubkey(),
            &spl_token_2022::id(),
        ),
        offramp_account: offramp_pda,
        token2022_program: spl_token_2022::id(),
        associated_token_program: spl_associated_token_account::id(),
        token_program: spl_token::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction(burn_bond_ix_args);

    let update_offramp_to_completed_ix = UpdateOfframpToCompleted {
        delegate_wallet: fake_delegate.pubkey(),
        delegate_account: find_delegate_pda(fake_delegate.pubkey()).0,
        offramp_account: offramp_pda,
        system_program: solana_program::system_program::id(),
    }
    .instruction();

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

    let error = et
        .context
        .banks_client
        .process_transaction(transaction)
        .await
        .err()
        .unwrap()
        .unwrap();

    match error {
        TransactionError::InstructionError(_, InstructionError::Custom(error_index)) => {
            let program_error = StablebondError::DelegateNotInitialized as u32;
            assert_eq!(error_index, program_error + 6000);
        }
        _ => {
            panic!("Wrong error occurs while testing fail_update_offramp_to_completed_when_delegate_doesnt_sign");
        }
    }
}
