import { api, API_CLIENT } from '../utils/api.ts';
import * as asserts from '@std/assert';
import { delete_user, EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from './helpers.ts';
import { generateTotp } from '../utils/totp.ts';

Deno.test({
	name: 'API - CHANNELS - 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 root_user_info = await get_new_user(client);

			try {
				const root_user_channel = await client.fetch('/channels', {
					method: 'POST',
					headers: {
						'x-session_id': root_user_info.session.id,
						'x-totp': await generateTotp(root_user_info.session.secret)
					},
					json: {
						name: 'this is the root user channel'
					}
				});

				asserts.assert(root_user_channel);
			} catch (error) {
				const reason: string = (error as Error).cause as string ?? (error as Error).toString();
				asserts.fail(reason);
			}

			const regular_user_info = await get_new_user(client, {}, root_user_info);

			try {
				const _permission_denied_channel = await client.fetch('/channels', {
					method: 'POST',
					headers: {
						'x-session_id': regular_user_info.session.id,
						'x-totp': await generateTotp(regular_user_info.session.secret)
					},
					json: {
						name: 'this should not be allowed'
					}
				});

				asserts.fail('allowed creation of a channel without channel creation permissions');
			} catch (error) {
				asserts.assertEquals((error as Error).cause, 'permission_denied');
			}

			await set_user_permissions(client, regular_user_info.user, regular_user_info.session, [...regular_user_info.user.permissions, 'channels.create']);

			try {
				const _too_long_name_channel = await client.fetch('/channels', {
					method: 'POST',
					headers: {
						'x-session_id': regular_user_info.session.id,
						'x-totp': await generateTotp(regular_user_info.session.secret)
					},
					json: {
						name: 'X'.repeat(1024)
					}
				});

				asserts.fail('allowed creation of a channel with an excessively long name');
			} catch (error) {
				asserts.assertEquals((error as Error).cause, 'invalid_channel_name');
			}

			const new_channel = await client.fetch('/channels', {
				method: 'POST',
				headers: {
					'x-session_id': regular_user_info.session.id,
					'x-totp': await generateTotp(regular_user_info.session.secret)
				},
				json: {
					name: 'test channel'
				}
			});

			asserts.assert(new_channel);

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