use bucketwarden_auth::{AccessKey, AuthError, AuthStore, CredentialRecord};

#[test]
fn local_users_and_service_accounts_can_own_access_keys() {
    let mut store = AuthStore::new();
    store.create_local_user("alice");
    store.create_service_account("backup-writer");

    store
        .put_access_key(AccessKey::active("alice", "AKIAALICE", "alice-secret"))
        .expect("alice key");
    store
        .put_access_key(AccessKey::active(
            "backup-writer",
            "AKIASERVICE",
            "service-secret",
        ))
        .expect("service key");

    assert_eq!(store.credential_count(), 2);
    assert_eq!(
        store
            .resolve_credential("AKIAALICE", 10)
            .expect("alice")
            .principal_id,
        "alice"
    );
    assert_eq!(
        store
            .resolve_credential("AKIASERVICE", 10)
            .expect("service")
            .principal_id,
        "backup-writer"
    );
}

#[test]
fn unknown_or_disabled_access_keys_do_not_resolve() {
    let mut store = AuthStore::new();
    store.create_local_user("alice");
    store
        .put_access_key(AccessKey::active("alice", "AKIAALICE", "alice-secret"))
        .expect("key");
    store.disable_access_key("AKIAALICE").expect("disable");

    assert!(matches!(
        store.resolve_credential("missing", 10),
        Err(AuthError::UnknownAccessKey(_))
    ));
    assert!(matches!(
        store.resolve_credential("AKIAALICE", 10),
        Err(AuthError::DisabledAccessKey(_))
    ));
}

#[test]
fn last_used_tracking_is_updated_by_explicit_mark_used() {
    let mut store = AuthStore::new();
    store.create_local_user("alice");
    store
        .put_access_key(AccessKey::active("alice", "AKIAALICE", "alice-secret"))
        .expect("key");

    store.mark_used("AKIAALICE", 42).expect("mark used");

    assert!(matches!(
        store.credential("AKIAALICE"),
        Some(CredentialRecord::AccessKey(key)) if key.last_used_epoch_seconds == Some(42)
    ));
}
