/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2025 Brett A C Sheffield <bacs@librecast.net> */

/* We don't really need much of an API for managing keys or keyrings, yet.
 * At the point where we need to manage and search large keyrings it might be
 * worth using different data structure, and then we will want functions to manage
 * keyrings */

#include "test.h"
#include <librecast/key.h>

int main(void)
{
	char name[] = "keyring API calls";
	lc_keypair_t key[8];
	lc_keyring_t keyring = {0};
	int nkeys = (int)(sizeof key / sizeof key[0]);
	int rc;

	test_name(name);

	rc = lc_keyring_init(&keyring, nkeys);

	/* add keys to keyring */
	for (int i = 0; i < nkeys; i++ ) {
		rc = lc_keypair_new(&key[i], LC_KEY_SIG);
		test_assert(rc == 0, "lc_keypair_new(LC_KEY_SIGN) [%i]", i);

		rc = lc_keyring_has(&keyring, key[i].pk);
		test_assert(rc == 0, "lc_keyring_has() - key[%i] not on ring before adding", i);

		rc = lc_keyring_add(&keyring, key[i].pk);
		test_assert(rc == 0, "lc_keyring_add()[%i]", i);
	}

	/* ensure all added keys on keyring */
	for (int i = 0; i < nkeys; i++ ) {
		rc = lc_keyring_has(&keyring, key[i].pk);
		test_assert(rc == -1, "lc_keyring_has() - key[%i] on ring after adding", i);
	}

	/* delete a key */
	const int idxdeleted = 5;
	rc = lc_keyring_del(&keyring, key[idxdeleted].pk);
	test_assert(rc == 0, "lc_keyring_del()");
	rc = lc_keyring_has(&keyring, key[idxdeleted].pk);
	test_assert(rc == 0, "lc_keyring_has() - key not on ring after deleting");
	errno = 0;
	rc = lc_keyring_del(&keyring, key[idxdeleted].pk);
	test_assert(errno == ENOKEY, "lc_keyring_del() - ENOKEY when key not exist");
	test_assert(rc == -1, "lc_keyring_del() - return -1 when key not exist");

	/* ensure other keys all still exist */
	for (int i = 0; i < nkeys; i++ ) {
		if (i == idxdeleted) continue;
		rc = lc_keyring_has(&keyring, key[i].pk);
		test_assert(rc == -1, "lc_keyring_has() - key[%i] on ring", i);
	}

	lc_keyring_free(&keyring);

	return test_status;
}
