import { api, API_CLIENT } from '../utils/api.ts';
import * as asserts from '@std/assert';
import { USER } from '../models/user.ts';
import { delete_user, EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, random_username } from './helpers.ts';
import { encodeBase64 } from '@std/encoding';

Deno.test({
	name: 'API - USERS - Create',
	permissions: {
		env: true,
		read: true,
		write: true,
		net: true
	},
	fn: async () => {
		let test_server_info: EPHEMERAL_SERVER | null = null;
		try {
			test_server_info = await get_ephemeral_listen_server();
			const client: API_CLIENT = api({
				prefix: '/api',
				hostname: test_server_info.hostname,
				port: test_server_info.port
			});

			const username = random_username();
			const password = 'password';
			const password_hash = encodeBase64(
				await crypto.subtle.digest('SHA-256', new TextEncoder().encode(password))
			);

			const info = await get_new_user(client, {
				username,
				password_hash
			});

			asserts.assert(info);
			asserts.assert(info.user);
			asserts.assert(info.session);
			asserts.assert(info.headers);

			const user: USER = info.user;

			asserts.assertEquals(user.username, username);

			await delete_user(client, info);
		} finally {
			if (test_server_info) {
				await test_server_info?.server?.stop();
			}
		}
	}
});
