// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use ed25519_dalek::SigningKey;
    use rialo_cdk::{
        constants::ConfigHashPrefix,
        generated::types::PublicKey,
        keyring::Keyring,
        transaction::{AccountMeta, Instruction, TransactionBuilder},
    };

    #[test]
    fn test_transaction_builder() {
        // Use OsRng for cryptographically secure random generation
        let keypair = SigningKey::generate(&mut rand::rngs::OsRng);
        let keyring = Keyring::new("test_keyring".to_string(), keypair, None, None);

        let payer = keyring.pubkey_string();

        // Get current time in milliseconds for valid_from
        let valid_from = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("Time went backwards")
            .as_millis() as i64;

        let pubkey = PublicKey::from_str(&payer).unwrap();
        let config_hash_prefix = ConfigHashPrefix::new(1);
        let mut builder = TransactionBuilder::new(pubkey, valid_from, config_hash_prefix);

        // Fix: Use a valid public key format (base58 encoded, 32 bytes)
        let program_id = PublicKey::from_str("11111111111111111111111111111111").unwrap();
        let instruction = Instruction {
            program_id,
            accounts: vec![
                AccountMeta {
                    pubkey: program_id,
                    is_signer: false,
                    is_writable: false,
                },
                AccountMeta {
                    pubkey: PublicKey::from_str(&keyring.pubkey_string()).unwrap(),
                    is_signer: true,
                    is_writable: true,
                },
            ],
            data: vec![0, 1, 2, 3],
        };

        builder.add_instruction(instruction);

        let _transaction = builder.build().unwrap();
        let _signed = builder.sign(&keyring).unwrap();

        // Assert the transaction has the correct structure
        // This will depend on the exact serialization format
    }

    #[test]
    fn test_transfer_instruction() {
        // Use valid base58-encoded public keys (32 bytes each)
        let from = PublicKey::from_str("11111111111111111111111111111112").unwrap();
        let to = PublicKey::from_str("11111111111111111111111111111113").unwrap();
        let amount = 1000;

        let instruction =
            rialo_cdk::transaction::instruction::transfer_instruction(&from, &to, amount);

        assert_eq!(
            instruction.program_id,
            PublicKey::from_str("11111111111111111111111111111111").unwrap()
        );
        assert_eq!(instruction.accounts.len(), 2);
        assert_eq!(instruction.accounts[0].pubkey, from);
        assert_eq!(instruction.accounts[1].pubkey, to);
    }
}
