/*
 * Utility functions used by unit tests
 *
 * User accounts
 */


/*
 * Find a test address
 */
CREATE FUNCTION _find_address( TEXT ) RETURNS INT AS $$
	SELECT id FROM users.addresses WHERE address = $1 || '@example.org';
$$ LANGUAGE SQL;


/*
 * Create a set of user addresses using some prefix
 */
CREATE FUNCTION _create_addresses( _quantity INT , _prefix TEXT )
		RETURNS VOID
	AS $$
DECLARE
	i	INT;
BEGIN
	i := 0;
	WHILE i < _quantity
	LOOP
		i := i + 1;
		BEGIN
			INSERT INTO users.addresses ( address )
				VALUES ( _prefix || i::TEXT || '@example.org' );
		EXCEPTION
			WHEN unique_violation THEN
				-- Address already exists, that's nice
		END;
	END LOOP;
END;
$$ LANGUAGE plpgsql;


/*
 * Create a set of user accounts
 */
CREATE FUNCTION _create_accounts( _quantity INT , _prefix TEXT )
		RETURNS VOID
	AS $$
DECLARE
	i	INT;
BEGIN
	PERFORM _create_test_strings( 0 );
	PERFORM _create_addresses( _quantity , _prefix );
	i := 0;
	WHILE i < _quantity
	LOOP
		i := i + 1;
		BEGIN
			INSERT INTO users.credentials (
				address_id , pass_md5 , pass_sha1 , language_id , credits
			) VALUES (
				_find_address( _prefix || i::TEXT ) , '' , '' , _get_language( 't' ) , 0
			);
		EXCEPTION
			WHEN unique_violation THEN
				-- Account already exists
		END;
	END LOOP;
END;
$$ LANGUAGE plpgsql;