mod program_test;
use {
    mpl_token_metadata::accounts::{MasterEdition, Metadata},
    program_test::StablebondProgramTest,
    solana_program_test::{tokio, ProgramTestContext},
    solana_sdk::{
        instruction::{Instruction, InstructionError},
        program_pack::Pack,
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        system_instruction,
        transaction::{Transaction, TransactionError},
    },
    spl_associated_token_account::get_associated_token_address,
    spl_token_2022::{instruction as token_instruction, state::Multisig},
    stablebond_sdk::{
        accounts::Issuance,
        errors::StablebondError,
        find_bond_multisig_meta_pda, find_bond_pda, find_config_pda, find_delegate_pda,
        find_issuance_pda, find_payment_feed_pda, find_payment_pda, find_payout_pda,
        instructions::{
            InitializeBond, InitializeBondInstructionArgs, InitializeConfig,
            InitializeConfigInstructionArgs, InitializeDelegate, InitializeIssuance,
            InitializeIssuanceInstructionArgs, MigrateMintAuthorityToMultisig, StartIssuance,
        },
        types::{OracleSetup, PaymentFeedType},
    },
};

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

async fn setup_issuance_day_from_now() -> 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 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_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(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_day_from_now: i64 = current_time + 60 * 60 * 24;
    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_day_from_now,
        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::UsdcUsd).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 ixs = &[
        initialize_config_ix,
        initialize_delegate_ix,
        initialize_bond_ix,
        initialize_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();
    ExecuteTestContext {
        context,
        admin,
        bond_mint,
    }
}

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 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_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(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_day_ago: i64 = current_time - (60 * 60 * 24);
    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_day_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::UsdcUsd).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 ixs = &[
        initialize_config_ix,
        initialize_delegate_ix,
        initialize_bond_ix,
        initialize_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();
    ExecuteTestContext {
        context,
        admin,
        bond_mint,
    }
}

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

    let recent_blockhash = et.context.last_blockhash;

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

    let transaction = Transaction::new_signed_with_payer(
        &[start_issuance_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        recent_blockhash,
    );

    // get issuance values before starting
    let account = et
        .context
        .banks_client
        .get_account(issuance_account)
        .await
        .unwrap()
        .unwrap();

    let issuance = Issuance::from_bytes(&account.data).unwrap();
    let estimated_start_datetime_before = issuance.estimated_start_datetime;
    let actual_start_datetime_before = issuance.actual_start_datetime;

    assert_eq!(actual_start_datetime_before, 0);

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

    // validate issuance values after starting
    let account = et
        .context
        .banks_client
        .get_account(issuance_account)
        .await
        .unwrap()
        .unwrap();

    let issuance = Issuance::from_bytes(&account.data).unwrap();

    // validate issuances are equal
    assert_eq!(
        issuance.status,
        stablebond_sdk::types::IssuanceStatus::Started,
    );
    assert_eq!(issuance.parent_bond, bond_account);
    assert_eq!(
        issuance.estimated_start_datetime,
        estimated_start_datetime_before
    );

    //validate the start_datetime changed
    assert_ne!(issuance.actual_start_datetime, actual_start_datetime_before);
}

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

    let recent_blockhash = et.context.last_blockhash;

    let bond_account = find_bond_pda(et.bond_mint.pubkey()).0;
    let issuance_number = 1;
    let issuance_account = find_issuance_pda(bond_account, issuance_number).0;

    migrate_to_multisig(&mut et).await;

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

    let transaction = Transaction::new_signed_with_payer(
        &[start_issuance_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        recent_blockhash,
    );

    // get issuance values before starting
    let account = et
        .context
        .banks_client
        .get_account(issuance_account)
        .await
        .unwrap()
        .unwrap();

    let issuance = Issuance::from_bytes(&account.data).unwrap();
    let estimated_start_datetime_before = issuance.estimated_start_datetime;
    let actual_start_datetime_before = issuance.actual_start_datetime;

    assert_eq!(actual_start_datetime_before, 0);

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

    // validate issuance values after starting
    let account = et
        .context
        .banks_client
        .get_account(issuance_account)
        .await
        .unwrap()
        .unwrap();

    let issuance = Issuance::from_bytes(&account.data).unwrap();

    // validate issuances are equal
    assert_eq!(
        issuance.status,
        stablebond_sdk::types::IssuanceStatus::Started,
    );
    assert_eq!(issuance.parent_bond, bond_account);
    assert_eq!(
        issuance.estimated_start_datetime,
        estimated_start_datetime_before
    );

    //validate the start_datetime changed
    assert_ne!(issuance.actual_start_datetime, actual_start_datetime_before);
}

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

    let other_wallet = Keypair::new();
    let other_wallet_pubkey = other_wallet.pubkey();

    let transfer_sol_ix = solana_program::system_instruction::transfer(
        &et.context.payer.pubkey(),
        &other_wallet_pubkey,
        1_000_000_000,
    );

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

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

    let recent_blockhash = et.context.last_blockhash;

    let start_issuance_ix = StartIssuance {
        delegate_account: find_delegate_pda(other_wallet_pubkey).0,
        delegate_wallet: other_wallet_pubkey,
        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(),
        token2022_program: spl_token_2022::id(),
        system_program: solana_program::system_program::id(),
    }
    .instruction();

    let transaction = Transaction::new_signed_with_payer(
        &[start_issuance_ix],
        Some(&other_wallet_pubkey),
        &[&other_wallet],
        recent_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 starting issuance");
        }
    }
}

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

    let recent_blockhash = et.context.last_blockhash;

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

    let transaction = Transaction::new_signed_with_payer(
        &[start_issuance_ix],
        Some(&et.admin.pubkey()),
        &[&et.admin],
        recent_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::IssuanceNotReadyToStart as u32;
            assert_eq!(error_index, program_error + 6000);
        }
        _ => {
            panic!("Wrong error occurs while testing initialize delegate");
        }
    }
}

pub fn create_multisig(
    payer: &Pubkey,
    multisig_account: &Pubkey,
    members: Vec<Pubkey>,
    threshold: u8,
) -> Vec<Instruction> {
    // Calculate the space needed for the multisig account
    let space = Multisig::get_packed_len();
    let rent = solana_sdk::rent::Rent::default();
    let lamports = rent.minimum_balance(space);

    // Create the account
    let create_account_ix = system_instruction::create_account(
        payer,
        multisig_account,
        lamports,
        space as u64,
        &spl_token_2022::id(),
    );

    // Convert members to the correct type
    let member_refs: Vec<&Pubkey> = members.iter().collect();

    // Initialize the multisig
    let init_multisig_ix = token_instruction::initialize_multisig(
        &spl_token_2022::id(),
        multisig_account,
        &member_refs,
        threshold,
    )
    .unwrap();

    // Return both instructions
    vec![create_account_ix, init_multisig_ix]
}

async fn migrate_to_multisig(et: &mut ExecuteTestContext) -> (Keypair, Pubkey) {
    // Create a new keypair for the multisig account
    let multisig_account = Keypair::new();
    let bond_pda = find_bond_pda(et.bond_mint.pubkey()).0;

    // Create multisig with Bond Mint PDA as member
    let create_multisig_ixs = create_multisig(
        &et.admin.pubkey(),
        &multisig_account.pubkey(),
        vec![bond_pda, Keypair::new().pubkey()], // randomly generated second member simulating a multisig with two members
        1,
    );

    // Create the migrate mint authority to multisig instruction
    let migrate_mint_authority_to_multisig_ix = MigrateMintAuthorityToMultisig {
        delegate_wallet: et.admin.pubkey(),
        delegate_account: find_delegate_pda(et.admin.pubkey()).0,
        mint_account: et.bond_mint.pubkey(),
        bond_account: find_bond_pda(et.bond_mint.pubkey()).0,
        bond_multisig_meta_account: find_bond_multisig_meta_pda(et.bond_mint.pubkey()).0,
        system_program: solana_program::system_program::id(),
        multisig_account: multisig_account.pubkey(),
        token2022_program: spl_token_2022::id(),
    }
    .instruction();

    // Combine all instructions
    let mut instructions = create_multisig_ixs;
    instructions.push(migrate_mint_authority_to_multisig_ix);

    // Send the transaction
    let recent_blockhash = et.context.last_blockhash;
    let transaction = Transaction::new_signed_with_payer(
        &instructions,
        Some(&et.admin.pubkey()),
        &[&et.admin, &multisig_account],
        recent_blockhash,
    );

    // Process the transaction
    et.context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    (multisig_account, bond_pda)
}
