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';

Deno.test({
	name: 'API - USERS - Update',
	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 info = await get_new_user(client);
			asserts.assert(info);

			const user = info.user;
			asserts.assert(user);

			const original_username = user.username;
			asserts.assertEquals(original_username, user.username);

			const updated_user: USER = await client.fetch(`/users/${user?.id}`, {
				method: 'PUT',
				json: {
					username: random_username()
				},
				headers: info.headers
			}) as USER;

			asserts.assert(updated_user);

			asserts.assertNotEquals(user.username, updated_user.username);
			asserts.assertNotEquals(user.timestamps.updated, updated_user.timestamps.updated);

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