use keychain_services::{AccessControl, AttrAccessible, AttrKeyClass,
                        AttrKeyType, Key, keychain, KeyPair, KeyPairGenerateParams};

fn main() {
    let keypair = generate_keypair(
        "rs.keychain-services.test.integration.query",
        "keychain-services.rs integration test query key",
    );

    let private_key_query = keychain::item::Query::new()
        .key_class(AttrKeyClass::Private)
        .key_type(AttrKeyType::EcSecPrimeRandom)
        .application_label(keypair.public_key.application_label().unwrap());

    let private_key = Key::find(private_key_query).unwrap();

    assert_eq!(
        keypair.private_key.application_label(),
        private_key.application_label()
    );
}

fn generate_keypair(tag: &str, label: &str) -> KeyPair {
    let acl =
        AccessControl::create_with_flags(AttrAccessible::WhenUnlocked, Default::default()).unwrap();

    let generate_params = KeyPairGenerateParams::new(AttrKeyType::EcSecPrimeRandom, 256)
        .access_control(&acl)
        .application_tag(tag)
        .label(label)
        .permanent(true);

    KeyPair::generate(generate_params).unwrap()
}
